MongoDB:更新子文档

时间:2011-04-13 09:04:50

标签: mongodb

我有这个系列:

[{ "_id" : 7,
   "category" : "Festival",
   "comments" : [
        {
                "_id" : ObjectId("4da4e7d1590295d4eb81c0c7"),
                "usr" : "Mila",
                "txt" : "This is a comment",
                "date" : "4/12/11"
        }
    ]
}]

我想要的只是在这样的评论中插入一个新字段:

[{ "_id" : 7,
   "category" : "Festival",
   "comments" : [
        {
                "_id" : ObjectId("4da4e7d1590295d4eb81c0c7"),
                "usr" : "Mila",
                "txt" : "This is a comment",
                "date" : "4/12/11",
                "type": "abc"  // find the parent doc with id=7 & insert this inside comments
        }
    ]
}]

如何在comments子文档中插入?

2 个答案:

答案 0 :(得分:77)

您需要使用the $ positional operator

例如:

update({ 
       _id: 7, 
       "comments._id": ObjectId("4da4e7d1590295d4eb81c0c7")
   },{
       $set: {"comments.$.type": abc}
   }, false, true
);

我没有测试它,但我希望它会对你有所帮助。

如果您想更改需要使用的文档结构

  

db.collection.update(条件,   objNew,upsert,multi)

     

参数:

criteria - query which selects the record to update;
objNew - updated object or $ operators (e.g., $inc) which manipulate the object
upsert - if this should be an "upsert"; that is, if the record does not exist, nsert it
multi - if all documents matching criteria should be updated

并插入具有新结构的新objNew。 check this for more details

答案 1 :(得分:3)

如果'comments'字段不是数组,$ position运算符只会按预期工作。 OP的json格式不正确,但看起来它可能是一个数组。

问题是mongodb现在只会更新与查询匹配的数组的第一个元素。虽然有一个RFE打开,可以添加对更新所有匹配数组元素的支持:https://jira.mongodb.org/browse/SERVER-1243

要解决这个数组问题,您只需要进行常规查找,然后单独更新数组中的元素。

相关问题