2

I've just started working with MongoDB. And I have a document like this:

   {

     "_id": "12345" 
     "body": "Here is the body" 
     "comments":[
                {
                  "name": "Person 1"
                  "comm": "My comment"},
                {
                  "name": "Person 2"
                  "comm": "Comment 2"}
             ] 
    "author":"Author 1" 
}

And I want to change this document to :

   {

    "_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" 
}

I've tried:

db.coll.update({ "_id":12345},{ "$set":{ "comments" :{ "checks_": 1}}})

And this removed all sub documents within comments and added {checks_:1} to it.

Where am I going wrong?

4

2 回答 2

7

所以你做错的是$set操作员正在做它应该做的事情,它只你指定的值替换字段。 这不是向数组添加额外的文档。comments

您需要具体并使用“点符号”来“识别”您要替换的数组元素。所以要得到你的结果,你需要两个更新:

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

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

于 2014-03-23T08:20:10.223 回答
1

更通用的解决方案(对于 MongoDb 3.6+):

db.coll.update(
{},
{$set: {"comments.$[element].checks_": 1}},
{multi: false, arrayFilters: [{"element.name": {$eq: "Person 1"}}]}
)

这会将字段添加到列表中的特定子文档中,匹配条件(名称 = 'Person 1')。

于 2018-09-28T20:40:55.063 回答