如何在 MongoDB 的子文档中添加额外的字段?

Sat*_*ian 2 mongodb mongo-shell

我刚刚开始使用 MongoDB。我有一个这样的文件:

   {

     "_id": "12345" 
     "body": "Here is the body" 
     "comments":[
                {
                  "name": "Person 1"
                  "comm": "My comment"},
                {
                  "name": "Person 2"
                  "comm": "Comment 2"}
             ] 
    "author":"Author 1" 
}
Run Code Online (Sandbox Code Playgroud)

我想将此文档更改为:

   {

    "_id": "12345" 
     "body": "Here is the body" 
     "comments":[
                {
                  "name": "Person 1"
                  "comm": "My comment"
                  "checks_": 1
                 },
                {
                  "name": "Person 2"
                  "comm": "Comment 2"
                  "checks_": 4
                }
             ] 
    "author": "Author 1" 
}
Run Code Online (Sandbox Code Playgroud)

我试过了:

db.coll.update({ "_id":12345},{ "$set":{ "comments" :{ "checks_": 1}}})
Run Code Online (Sandbox Code Playgroud)

这删除了评论中的所有子文档并添加{checks_:1}到其中。

我哪里错了?

Nei*_*unn 6

所以,你在做什么错的是,$set运营商正在做什么应该和它取代 comments用您指定的值字段。这不是向数组添加额外的文档。

您需要具体并使用“点符号”来“识别”您要替换的数组元素。因此,要获得结果,您需要进行两次更新:

db.coll.update({ "_id":12345},{ "$set":{ "comments.0.checks_" : 1 }})
db.coll.update({ "_id":12345},{ "$set":{ "comments.1.checks_" : 4 }})
Run Code Online (Sandbox Code Playgroud)

至少在 MongoDB 的下一个版本(截至撰写时)发布之前,您可以进行批量更新。现在不会太久了。