2015-12-08 88 views
1

我在一个项目oj NodeJS中工作,我想删除一个包含objets的数组元素。删除一个包含对象的数组MongoDB

的模式是:

{ 
 
    "products" : [ 
 
    { 
 
     "productid" : 1, 
 
     "name" : "product 1", 
 
     "price" : 200 
 
     
 
    }, 
 
    { 
 
     "productid" : 2, 
 
     "name" : "product 2", 
 
     "price" : 300 
 
     
 
    }, 
 
    { 
 
     "productid" : 3, 
 
     "name" : "product 3", 
 
     "price" : 350 
 
     
 
    }, 
 
    { 
 
     "productid" : 4, 
 
     "name" : "product 4", 
 
     "price" : 300 
 
     
 
    }, 
 
, 
 
    { 
 
     "productid" : 5, 
 
     "name" : "product 5", 
 
     "price" : 300 
 
     
 
    } 
 
    
 
    ] 
 
}

,我想删除产品3,如何查询是在MongoDB中? “productid”属性是关键,不重复它

谢谢。

回答

1

使用此:

变化collection名和{}根据自己的需要。

db.collection.update({}, { "$pull" : { "products" : { "productid" : 3 } } }); 

如果多个元素相匹配,然后使用多选项等

db.collection.update({}, { "$pull" : { "products" : { "productid" : 3 } } }, 
{ multi: true }); 
0
db.collection.update({<query>}, { "$pull" : { "products.productid" : 3 } }); 
相关问题