I am working with a complex mongodoc that has several embedded documents that represent items in an inventory. The whole document can be thought of as a complete inventory. The key 'sections' contains another key 'items' that contains the individual items and their data such as price, description etc. Each item also has a GUID so it can be looked up individually.
I wrote a stored function to hunt for individual items by id that looks like this:
function (item_id) {
var pls = db.pricelists.findOne({'sections.items.item_id':item_id});
if (!pls) {
return null;
}
for (var sect in pls.sections) {
for (var item in pls.sections[sect].items) {
if (pls.sections[sect].items[item].item_id == item_id) {
return pls.sections[sect].items[item];
}
}
}
}
Everything works find so far. The problem is when I want to modify this embedded doc and save it back within its parent document. Examples given from the shell:
var item = db.eval('find_item(1)');
item.users_who_bought = [11,16];
item;
This prints back out to the console the correct item.
{
"name" : "item00",
"order" : 0,
"item_id" : 1,
"hidden" : false,
"variants" : [
{
"price" : "0.56",
"label" : "variant000"
},
{
"price" : "1.56",
"label" : "variant001"
},
{
"price" : "2.56",
"label" : "variant002"
}
],
"desc" : "Sociis habitasse, integer pellentesque sit! Nisi purus tincidunt amet mus scelerisque amet, pid enim eros phasellus dolor sociis nunc dictumst sed nunc, integer hac!",
"users_who_bought" : [11,16]
}
I am at a loss as how to formulate the query to update this embedded item document back into its parent doc. I have tried something like this (the item_id is hardcoded as one here for example):
db.pricelists.update({'sections.item.item_id': 1}, {$set: {'sections.item.item_id[1]': item}})
But this does not work correctly and tries to append to the items array.
Is there a way to wholesale pass in a modified embedded document to an update statement like this, selectively by a value within the document? Or am I thinking about this the wrong way, and I'll need to write another stored iterator function that will find the item again and then update the entire parent doc with the new values deeply embedded? Thanks!