简体   繁体   English

所有文档中的mongoDB +节点更新字段

[英]mongoDB + Node update field from all documents

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 我想为包含_id 531ed22ae604d3d30df8e2ca的项目的所有文档将数量设置为0

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.. 但我认为查询不好..

您需要使用“$”位置运算符来实现此目的:

db.warehouses.update({"items._id": "531ed22ae604d3d30df8e2ca"}, { $set: { "items.$.qty":0} } )

In the mongo console it would look like this: 在mongo控制台中,它看起来像这样:

do {
  db.warenhouse.update(
    {
      "_id" : "531cc2410b4ebf000036b2d7",
      items: {
        $elemMatch: {
          qty: { $ne: 0 }
        }
      }
    },
    {
      $set: {
        "items.$.qty": 0
      }
    }
  )
} while (db.getPrevError().n != 0);

Resource link 资源链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM