I have this collection: {_id, list}
I have the elements in the list, of which each has an _id of its own, but I can't figure out how to update all the elements in the list. I do know that all collections have unique elements in the list, including amongst themselves. And I have the elements with updated properties :|
Hope I explained it clearly.
I hope I've got your problem right.
Suppose, you want to update given sub-document in the list by its _id, but you don't know its parent's _id.
To make an update operation you may use the following command:
db.collection.update({
'list._id': subdoc_id
},{
$set: {
'list.$.field1': value1,
'list.$.field2': value2,
'list.$.field3': value3
}
})
To replace an old sub-document with the new one (equivalent of save):
db.collection.update({
'list._id': subdoc._id
},{
$set: {
'list.$': subdoc
}
})
But you should be aware that this operation will completely erase the old sub-document and replace it with the new one. So, any field not listed in subdoc will be deleted.
{'list._id': subdoc_id} query will find you a parent document containing the given sub-document and 'list.$' selector will point to the queried sub-document.
Update: If you don't know in wich particular list the given sub-document is stored, you'll need to run an update operation on each:
['list1', 'list2', 'nested.list'].forEach(function (list) {
var query = {};
query[list+'._id'] = subdoc._id;
var update = { $set: {} };
update.$set[list+'.$'] = subdoc;
db.collection.update(query, update);
})
An update will be performed on each list where the given sub-document is present.