Add property to nested array in mongodb document

I have a mongodb file with the following structure

> db.user.find().limit(1); { "_id" : "1", "foo" : { "bars" : [ { "name" : "bar1" }, { "name" : "bar2" }, ], ... }, ... } 

I want to add a new property to each bar . I have my script iterate over a bars array, but I cannot get a new property there, how can I do this?

 var users = db.user.find({"foo.bars":{$exists:true}}); users.forEach(function(user) { user.foo.bars.forEach(function(bar) { printjson(bar); //how can I specify the current 'bar' in this update? //db.experience.update({_id: user._id}, {$set: {"what goes here?" : "newbarValue"}}); }); }); 
+4
source share
3 answers

So says the preacher:

 var users = db.user.find({"foo.bars":{$exists:true}}); users.forEach(function(user) { var id = user._id; var foo_bars = user.foo.bars; var new_foo_bars = []; for(var i = 0; i < foo_bars.length; i++) { var foo_bar = foo_bars[i]; foo_bar['newkey'] = 'newvalue'; new_foo_bars.push(foo_bar); } db.user.update({"_id":id}, {$set:{"foo.bars":new_foo_bars}}); }); 
+10
source

I noticed that you are scrolling an array on the client side there in JS.

If you were to create a new array of "bars" from the old, then click it as a whole new value, this would mean that you only make one DB call, and the code is pretty elegant.

If MongoDB does not usually support it, it is best to just do the work on the client side.

+1
source

You must update each element of the attached document individually. Using the positioning operator "$" will not work, since it will only work in the first match (as described).

0
source

All Articles