MongoDB:更新子文档

khe*_*eya 44 mongodb

我有这个系列:

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

我想要的是在这样的注释中插入一个新字段:

[{ "_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
        }
    ]
}]
Run Code Online (Sandbox Code Playgroud)

如何在comments子文档中插入?

And*_*ich 79

您需要使用$ position运算符

例如:

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

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

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

db.collection.update(criteria,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
Run Code Online (Sandbox Code Playgroud)

并插入具有新结构的新objNew.请查看此内容以获取更多详

  • 请注意,因为用于更新的MongoDB ver 2.2语法是db.collection.update(<query>,<update>,{upsert:<boolean>,multi:<boolean>}) (3认同)