Reputation: 12346
i need to update one field from a subdocument that appears inside other documents for all documents...
Something like this, i have some documents like this:
{
"_id": { "$oid" : "531cc2410b4ebf000036b2d7" },
"name": "ALMACEN 2",
"items": [
{
"_id": { "$oid" : "531ed4cae604d3d30df8e2ca" },
"brand": "BJFE",
"type": 0,
"color": "GDRNCCD",
"hand": 1,
"price": 500,
"model": 0,
"qty": 24
},
{
"_id": { "$oid" : "531ed4cae604d2330df8e2ca" },
"brand": "BJFE",
"type": 0,
"color": "GDRNCCD",
"hand": 1,
"price": 500,
"model": 0,
"qty": 12443
},
{
"_id": { "$oid" : "531ed22ae604d3d30df8e2ca" },
"brand": "BJFE",
"type": 0,
"color": "GDRNCCD",
"hand": 1,
"model": 0,
"price": 500,
"qty": 5
}
]
}
I want to set the qty to 0 for all documents that contains the item with _id 531ed22ae604d3d30df8e2ca
At moment i have it
warehouses.update({$.items._id: new ObjectID(item.brand._id)}, { $set: { qty: 0}}, {safe: false, multi: true}, function (e) {
if (e) {
error(e);
return;
}
success();
});
But i think the query is not ok..
Upvotes: 0
Views: 76
Reputation: 14280
In the mongo console it would look like this:
do {
db.warenhouse.update(
{
"_id" : "531cc2410b4ebf000036b2d7",
items: {
$elemMatch: {
qty: { $ne: 0 }
}
}
},
{
$set: {
"items.$.qty": 0
}
}
)
} while (db.getPrevError().n != 0);
Resource link
Upvotes: 0
Reputation: 12934
You'll need to use the "$" positional operator to achieve this:
db.warehouses.update({"items._id": "531ed22ae604d3d30df8e2ca"}, { $set: { "items.$.qty":0} } )
Upvotes: 2