【问题标题】:Insert field into an array of sub-documents. unexpected behaviour将字段插入到子文档数组中。意外行为
【发布时间】:2015-11-28 20:23:39
【问题描述】:

我正在尝试在每个子文档数组的每个子文档中插入一个新字段。我有一个半工作脚本,预期的结果是 ordinal_number 要插入到每个子文档中,但它似乎是插入到集合中每个 comments 数组中的第一个子文档中。

db.posts.find({
"comments.ordinal_number":{"$exists":true}}).forEach(function(data){
   for(var i = 0; i < data.comments.length; i++) {
     db.posts.update(
    { 
         "_id": data._id, 
         "comments.body": data.comments[i].body
     },
     {
         "$set": {
           "comments.$.ordinal_number":
               1
         }
     },true,true
    );
  }
});

输出结果:

    "link" : "cxzdzjkztkqraoqlgcru",
        "author" : "machine",
        "title" : "arbitrary title",
        "comments" : [
            {
                "body" : "...",
                "email" : "ZoROirXN@thUNmWmY.com",
                "author" : "Foo bar",
                "ordinal_number" : 1
            },
            {
                "body" : "...",
                "email" : "eAYtQPfz@kVZCJnev.com",
                "author" : "Foo baz"
            }
]

【问题讨论】:

  • @user3100115 我想添加一个实际的新字段,而不是更新字段的值。

标签: javascript mongodb mongodb-query


【解决方案1】:

您还需要循环游标和数组条目,然后使用 $ 运算符使用 "bulk" 操作更新数组中的每个子文档,以获得最大效率。

var bulk = db.posts.initializeOrderedBulkOp();
var count = 0;
db.posts.find().forEach(function(doc) { 
    var nComments = doc.comments.length; 
    for (var i = 0; i < nComments; i++) {
        bulk.find( { 
            '_id': doc._id, 
            'comments': { '$elemMatch': { 'email': doc.comments[i]['email'] } }
        } ).update({
            '$set': { 'comments.$.ordinal_number': 1 } 
        }) 
    } 
    count++;
    if(count % 200 === 0) {   
        // Execute per 200 operations and re-init
        bulk.execute();     
        bulk = db.posts.initializeOrderedBulkOp(); 
     }
})

// Clean up queues.
if (count > 0)  bulk.execute();

请注意,批量 API 是 2.6 中的新功能,因此如果您使用的是旧版本,则需要使用 .update() 方法。

db.posts.find().forEach(function(doc) { 
    var nComments = doc.comments.length; 
    for (var i = 0; i < nComments; i++) {
        db.posts.update( 
            { 
                '_id': doc._id, 
                 'comments': { '$elemMatch': { 'email': doc.comments[i]['email'] } }
            }, 

            { '$set': { 'comments.$.ordinal_number': 1 } }
         ) 
    } 
})

【讨论】:

    猜你喜欢
    • 2016-12-09
    • 1970-01-01
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    • 2016-10-16
    • 2017-09-14
    • 2023-04-05
    • 1970-01-01
    相关资源
    最近更新 更多