I want to add (+1) a qty field inside a collection with documents like this:
{"_id": { "$oid" : "531cc2410b4ebf000036b2d7" },
"name": "ALMACEN 2",
"items": [
{
"id": "111111",
"marca": "BJFE",
"tipo": 0,
"color": "GDRNCCD",
"mano": 1,
"modelo": 0,
"qty": 1
},
{
"marca": "BJddFE",
"tipo": 0,
"color": "GDffRNCCD",
"mano": 1,
"modelo": 0,
"qty": 3
},
{
"marca": "BJeeFE",
"tipo": 0,
"color": "GDRNCCD",
"mano": 1,
"modelo": 0,
"qty": 9
} ] }
I want to add +1 to qty in the document with _id = 531cc2410b4ebf000036b2d7 and inside items, with id=1111.
Is it possible?
EDIT:
with this code
warehouses.update(
{_id: new ObjectID(warehouseId)},
{"$inc": { "items.$.qty": -1 }},
function (e, docs) {
if (e) {
error(e);
return;
}
success(docs);
});
I have error:
cannot apply the position operator without a corresponding query field containing an array
Finally this works:
warehouses.update({_id: new ObjectID(warehouseId), "items.id": itemId}, {"$inc": { "items.$.qty": -1 }}, function (e) {
if (e) {
error(e);
return;
}
success();
});
Yes. Just use $inc and the positional $
operator:
db.collection.update(
{ _id: <matching id>, "items.id": 1111 },
{ "$inc": { "items.$.qty": 1 } }
)
The $
matches the index of the element you matched in the query part of your update. This allows the update portion of the statement to know which element in the array to address.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With