2017-08-15 59 views
0

一个数组的多个项目,这是我的文档模式:如何更新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]; 

所以,我怎么可以更新的内部产品的详细信息,其ID在product_ids阵列中的所有产品只是product_status。

回答

2

这应该为你工作:

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] } }); 
} 
+0

是这将解决我的问题,但在这里,我将不得不做多个更新的要求,但我用collection.save在[https://stackoverflow.com/questions/4669178/how-to-update-multiple-array-elements-in-mongodb(]如何在mongodb中更新多个数组元素) –