【问题标题】:MongoDB shell: How to remove specific elements in all the collections inside a DBMongoDB shell:如何删除数据库内所有集合中的特定元素
【发布时间】:2015-11-16 11:07:42
【问题描述】:

我想删除所有集合中所有与正则表达式的巧合。

我需要这个,因为今天我的应用程序中的 JSON 解析器失败了,现在数据库已损坏。

我可以手动完成,但我有超过 100 个集合,并且手动输入 mongo shell db["X"].remove({ "DateTime": { $regex : "2015-11-16" } }) 每个集合都需要相当长的时间。

您知道在 mongo shell 中自动执行此操作的任何方法吗?我总是通过 R 中的包 RMongo 访问这个数据库,我可以通过 dbRemoveQuery(rmongo.object, collection, query) 来访问这个数据库,但我想知道它是否可以在 mongo shell 中完成,可能会更快一些。

【问题讨论】:

    标签: javascript mongodb mongodb-query mongodb-shell


    【解决方案1】:
    use yourDbName
    
    // Get the names of all collections in the database.
    var names = db.getCollectionNames();
    
    // Iterate over every collection name.
    for(i = 0; i < names.length; i++) {
    
        // Only issue the query if the collection is not a system collection.
        if(!names[i].startsWith("system.")) {
    
            // Issue the query against the collection with the name `names[i]`.
            db[names[i]].remove({ "DateTime": { $regex : "2015-11-16" } });
        }
    }
    

    请注意,我将system collections 从列表中排除。

    【讨论】:

      【解决方案2】:

      在 mongo shell 中:

       db.getCollectionNames().forEach(function(name) {
           db[name].remove({ "DateTime": { $regex : "2015-11-16" } });
       })
      

      【讨论】:

      • 感谢您的努力,但是(不知道为什么)表现不佳。
      • @Sergio 我已经修复了这个答案。现在它也可以工作了。
      • 谢谢,不过)不见了没问题,失败后我把它放了,但之后我检查了收藏,文件还在。
      • @Sergio 关闭 ) 不是我唯一修复的东西 ;-) 我还在回调函数中添加了 name 参数并像这样使用它:db[name]。跨度>
      【解决方案3】:

      .startsWith() 是一项新技术,是 ECMAScript 2015 (ES6) 标准的一部分,因此它可能无法在 Mongo Shell 中运行。

      您将需要使用.filter() 方法来丢弃系统集合

      var collections = db.getCollectionNames().filter(function(collection) {
          return collection.indexOf('system.') !== -1;
      };
      

      然后在此处删除符合您条件的文档"DateTime": "2015-11-16"

      for(var index=0; index < collections.length; index++) {
          db[collections[index]].remove( { 'DateTime': /2015-11-16/ } )
      }
      

      【讨论】:

        猜你喜欢
        • 2021-02-14
        • 2018-03-04
        • 2023-01-13
        • 1970-01-01
        • 1970-01-01
        • 2011-03-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多