Question

I have created an array in my mongo document, so it looks a bit like the following:

{ "_id" : ObjectId("4f59e19d0b7aab2903000004"), 
  "details" : { x:1, y:2 }
}

I am then trying to push a new value to the array, doing:

db.users.update({"_id" : ObjectId("4f59e19d0b7aab2903000004")},{$push: {"details": {"z":3}}});

However I get the error:

Cannot apply $push/$pushAll modifier to non-array

It seems the only way I am actually able to add the information to the array, is to use dot notation to add it, e.g.

db.users.update({"_id" : ObjectId("4f59e19d0b7aab2903000004")},{"details.z": 3});

That seems to work, but when I have an array of about 30 values, it seems a bit tedious.

Just for clarity, I am using the lithium PHP framework, not just entering these manually, so I could loop through an array to prepend the 'details.' to each key, but I don't think that should be necessary. Is there something I'm missing as to why it won't push values into the array?

(My lithium code was as follows:)

User::update(array('$push'=>array('details'=>array('z'=>3))), array('_id'=>$id))

Thanks,

Dan

Was it helpful?

Solution

"details" is an embedded document, not an array. If it was an array it would look like this (note the [] indicating an array):

{ "_id" : ObjectId("4f59f0531ae8f3b5f92246fe"), 
       "details" : [ { "x" : 1 }, { "y" : 2 } ] }

If you then do a $push:

db.users.update({"_id" : ObjectId("4f59f0531ae8f3b5f92246fe")}, 
                {$push : {"details": {"z":3}}})

You get the expected result:

db.users.find({"_id" : ObjectId("4f59f0531ae8f3b5f92246fe")})

{ "_id" : ObjectId("4f59f0531ae8f3b5f92246fe"), 
  "details" : [ { "x" : 1 }, { "y" : 2 }, { "z" : 3 } ] }

Basically you are trying to push to a document, not an array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top