0

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..

colymore
  • 11,776
  • 13
  • 48
  • 90

2 Answers2

2

You'll need to use the "$" positional operator to achieve this:

db.warehouses.update({"items._id": "531ed22ae604d3d30df8e2ca"}, { $set: { "items.$.qty":0} } )
Anand Jayabalan
  • 12,294
  • 5
  • 41
  • 52
0

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

Community
  • 1
  • 1
czerasz
  • 13,682
  • 9
  • 53
  • 63