I was trying to push to a nested array in MongoDB 3.0.4. This will illustrate the problem- here is a document in the characters collection and I want to add image_4 to Elmer's images array:
{
"_id" : ObjectId("56084e91981824fc51693e72"),
"firstname" : "Elmer",
"lastname" : "Fudd",
"company" : "Warners",
"password" : "4567",
"galleries" : [
{
"gallery" : "1",
"images" : [
"image_1",
"image_2",
"image_3"
]
}
]
}
Firstly I tried:
db.characters.update({"firstname":"Elmer"},{$push {"galleries.$.images":"image_4"}})
and got the error:
"writeError" : {
"code" : 16837,
"errmsg" : "The positional operator did not find the match needed from the query. Unexpanded update: galleries.$.images"
Then I saw a solution on SO Update an item in an array that is in an array and tried:
db.characters.update({"firstname":"Elmer"},{$push:{"galleries.0.images":"image_4"}})
which worked fine. I understand that the positional operator $ cannot be used with nested arrays, but why does its substitution with 0 work, and what is 0 in this usage? I can't find it in the Mongodb docs.