Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update field inside document by id in MongoDB

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();
    });
like image 755
colymore Avatar asked Mar 12 '14 15:03

colymore


1 Answers

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.

like image 196
Neil Lunn Avatar answered Sep 20 '22 19:09

Neil Lunn