【问题标题】:Loop through Mongo Collection and update a field in every document循环遍历 Mongo Collection 并更新每个文档中的字段
【发布时间】:2016-02-05 10:47:09
【问题描述】:

我在一个集合中插入了错误的日期,并且是简单的"2015-09-10" 字符串 格式。

我想更新它们以更正 ISO 日期格式

我尝试使用 forEach() 在 Mongo 中循环,但我不太了解 shell 如何更新集合中的每个文档。

到目前为止,我在这一点上:

db.getCollection('schedules').find({}).forEach(function (doc) {

    doc.time = new Date( doc.time ).toUTCString();

    printjson( doc.time );
    // ^ This just prints "Invalid Date"

    // Also none of the below work when I try saving them

    //doc.save();
    //db.getCollection('schedules').save(doc);
});

这里缺少什么?

【问题讨论】:

    标签: node.js mongodb mongodb-query


    【解决方案1】:

    只需使用 .find() 编写一个 for 循环,然后更新每个结果。例如,在 Python/PyMongo 中,假设我们有一个名为“movies”的集合,我们希望通过添加一个名为“reviews”的字段来更新它,我们希望其值是一个包含 5 个具有“name”和“rating”的对象的数组' 字段。我们将使用 Faker 和 random 为这些字段创建一些随机信息:

    from pymongo import MongoClient 
    from faker import Faker 
    faker = Faker()
    import random
    
    client = MongoClient()
    db = client.test
    
    for res in db.movies.find():
        db.movies.updata_one(res, {'$set':{'reviews':[{'name':faker.name(), 'rating': random.randint(1,5)} for _ in range(5)]}})
    

    请注意,如果您使用的是原生 Mongo,那么您应该使用 updateOne 而不是 update_one。我认为类似的方法适用于 JavaScript,只是使用 for (let res of db.movi​​es.find()) 语法

    【讨论】:

      【解决方案2】:

      最好的方法是使用"Bulk" 操作

      var collection = db.getCollection('schedules');
      var bulkOp = collection.initializeOrderedBulkOp();
      var count = 0;
      collection.find().forEach(function(doc) {
          bulkOp.find({ '_id': doc._id }).updateOne({
              '$set': { 'time': new Date(doc.time) }
          });
          count++;
          if(count % 100 === 0) {
              // Execute per 100 operations and re-init
              bulkOp.execute();
              bulkOp = collection.initializeOrderedBulkOp();
          }
      });
      
      // Clean up queues
      if(count > 0) {
          bulkOp.execute();
      }
      

      【讨论】:

      • 哇,谢谢,所以这与我预期的有点不同。几乎类似于猫鼬。 bulkOp.execute的目的是一次批量更新100条记录吗? @user3100115
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-29
      • 1970-01-01
      • 1970-01-01
      • 2013-01-26
      • 1970-01-01
      • 2019-09-02
      相关资源
      最近更新 更多