问题
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?
回答1:
So what you are doing wrong is that the $set operator is doing exactly what it should, and it is replacing only the comments
field with the value you have specified. This is not adding an additional document to the array.
You need to be specific and use "dot notation" to "indentify" which array element you are replacing. So to get to your result, you need two updates:
db.coll.update({ "_id":12345},{ "$set":{ "comments.0.checks_" : 1 }})
db.coll.update({ "_id":12345},{ "$set":{ "comments.1.checks_" : 4 }})
That is at least until the next version (as of writing) of MongoDB is released, where you can do bulk updates. And that will not be long now.
回答2:
A little more geneirc solution (for MongoDb 3.6+):
db.coll.update(
{},
{$set: {"comments.$[element].checks_": 1}},
{multi: false, arrayFilters: [{"element.name": {$eq: "Person 1"}}]}
)
This will add field into specific sub document from the list, matching criteria (name = 'Person 1').
来源:https://stackoverflow.com/questions/22588236/how-to-add-an-extra-field-in-a-sub-document-in-mongodb