How to add an extra field in a sub document in MongoDB?
mongo-shell, mongodb
Solution
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.
Problem
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?