如何在 mongodb 中更新数组的多个项目

How to update multiple items of a array in mongodb

这是我的文档架构:

  {
        "_id": "599345434a6caf2d9d2e2b67",
        "total": 870,
        "product_info": [
            {
                "product_id": "597de6e76dbf1a0004b98eb5",
                "mrp": 20,
                "quantity": 1,
                "name": "bottle",
                "product_status": 1
            },
            {
                "product_id": "597dea4c6dbf1a0004b98eba",
                "mrp": 300,
                "quantity": 1,
                "name": "purse",
                "product_status": 1
            },
            {
                "product_id": "597dea7d6dbf1a0004b98ebb",
                "mrp": 250,
                "quantity": 1,
                "name": "switch board",
                "product_status": 1
            },
            {
                "product_id": "597deade6dbf1a0004b98ebc",
                "mrp": 150,
                "quantity": 1,
                "name": "all out",
                "product_status": 1
            },
            {
                "product_id": "597deb196dbf1a0004b98ebd",
                "mrp": 150,
                "quantity": 1,
                "name": "neem extract",
                "product_status": 1
            }
        ],
        "shop_id": "597de6056dbf1a0004b98eb4",
        "shop_name": "Pradeep's Shop",
        "seller_uid": "469835666700",
        "user_id": "598b9b700354020004f674b6",
        "user_name": "bhupendra",
        "payment_id": "NA",
        "address_id": "NA",
        "payment_type": 1,
        "address_type": 1,
        "start_date": "2017-08-15T18:53:38.976Z",
        "last_update_date": "2017-08-15T19:02:27.245Z",
        "order_status": 1,
        "delivery_status": 1,
        "payment_status": 1,
        "delivery_date": "NA",
        "payment_date": "NA"
    }

在我的查询中,我将发送 product_id 我需要更新的列表和 product_status 我需要更改的列表,例如

var product_ids=["597de6e76dbf1a0004b98eb5","597dea7d6dbf1a0004b98ebb"];
var product_status=[2,3];

那么我如何才能只更新 product_info 中所有产品的 product_status,其 ID 在 product_ids 数组中。

这应该适合你:

var bhupendra = localdb.collection('bhupendra');

var product_ids=["597de6e76dbf1a0004b98eb5","597dea7d6dbf1a0004b98ebb"];
var product_status=[2,3];

for (var i = 0; i < product_ids.length; i++) {
  bhupendra.update({_id: "599345434a6caf2d9d2e2b67", "product_info.product_id": product_ids[i]}, { $set: { "product_info.$.product_status" : product_status[i] } });
}