Error updating array in Mongo

I created an array in my mongo document, so it looks something like this:

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

Then I try to push the new value to the array by doing:

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

However, I get the error message:

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

It seems the only way I can really add information to an array is to use dot notation to add it, for example.

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

This seems to work, but when I have an array of about 30 values, it looks a little tedious.

Just for clarity, I use the lithium PHP framework, and not just enter them manually, so I could iterate over the array to add โ€œdetailsโ€. for every key, but I donโ€™t think it is necessary. Is there something that I'm missing, why won't it insert values โ€‹โ€‹into an array?

(My lithium code was as follows :)

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

Thanks,

Dan

+4
source share
1 answer

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

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

If you then do $ push:

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

You will 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 click on a document, not an array.

+4
source

Source: https://habr.com/ru/post/1400564/


All Articles