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.
{"firstname":"Elmer", "galleries.gallery":1}in the query portion of your update so you actually match the required element.$operator at all. In order to use the positional operator you need to match an element in the array and then specifiy the operator within the update portion. Just alter the first query you wrote to also include a match for the array element."1"instead. This is all plainly stated in the documentation or it is just plain typing mistakes or mixed types. As was the original error message quite clear as to what was missing.