The question and the OP example do not match. He really wants to insert a field into an array inside the document, which means that
db.posts.update({name: "Hello, world!" }, { $push: {comments: "First comment!"}});
works great.
However, if you want to add a value or subdocument to the dictionary, you must use the command $set. Take this document as our example:
{
"_id": {
"$oid": "538420b2862a656e9e99fc93"
},
"name": "Farmer John",
"items": {
"peaches": 5,
"bananas": 10
}
}
, "apples": 2 .
db.collection.update({"name": "Farmer John"},
{"$set": {"items.apples": 2}});
:
{
"_id": {
"$oid": "538420b2862a656e9e99fc93"
},
"name": "Farmer John",
"items": {
"peaches": 5,
"bananas": 10,
"apples: 2
}
}
, , :
{
"_id": {
"$oid": "538420b2862a656e9e99fc93"
},
"name": "Farmer John",
"items": {
"peaches": {
"yellow": 5,
"white": 3
}
}
}
4 8 -.
db.collection.update({"name": "Farmer John"},
{"$set": {"items.apples": {"fuji": 8, "granny smith": 4}}});
:
{
"_id": {
"$oid": "538420b2862a656e9e99fc93"
},
"name": "Farmer John",
"items": {
"peaches": {
"yellow": 5,
"white": 3
},
"apples": {
"fuji": 8,
"granny smith": 4
}
}
}
: , , $set.