MongoDB, remove object from array

2019-01-01 05:47发布

Doc:

{
   _id: 5150a1199fac0e6910000002,
   name: 'some name,
   items: [{
      id: 23,
      name: 'item name 23'
   },{
      id: 24,
      name: 'item name 24'
   }]
}

Is there a way to pull a specific object from an array? I.E. how do I pull the entire item object with id 23 from the items array.

I have tried:

db.mycollection.update({'_id': ObjectId("5150a1199fac0e6910000002")}, {$pull: {id: 23}});

However I am pretty sure that I am not using 'pull' correctly. From what I understand pull will pull a field from an array but not an object.

Any ideas how to pull the entire object out of the array.

As a bonus I am trying to do this in mongoose/nodejs, as well not sure if this type of thing is in the mongoose API but I could not find it.

5条回答
后来的你喜欢了谁
2楼-- · 2019-01-01 06:06

You can try it also:

db.getCollection('docs').update({ },{'$pull':{ 'items':{'id': 3 }}},{multi:true})
查看更多
旧时光的记忆
3楼-- · 2019-01-01 06:12

try..

db.mycollection.update(
    {'_id': ObjectId("5150a1199fac0e6910000002")}, 
    { $pull: { "items" : { id: 23 } } },
false,
true 
);
查看更多
不流泪的眼
4楼-- · 2019-01-01 06:16

Use $pull to remove the data

return this.mobiledashboardModel
.update({"_id": args.dashboardId}, { $pull: {"viewData": { "_id": widgetId}}})
.exec()
.then(dashboardDoc => {
     return {
        result: dashboardDoc
     }
});
查看更多
爱死公子算了
5楼-- · 2019-01-01 06:17
my database:->
        {
       "_id" : ObjectId("5806056dce046557874d3ab18"),
       "data" : [ 
           {
               "id" : 1
           }, 
           {
               "id" : 2
           }, 
           {
               "id" : 3
           }
       ]
    }

MY QUERY:->
db.getCollection('play_table').update({},{$pull:{"data":{"id":3}}},{multi:true}
OutPut:->
{
  "_id" : ObjectId("5806056dce046557874d3ab18"),
       "data" : [ 
           {
               "id" : 1
           }, 
           {
               "id" : 2
           }
       ]
    }
查看更多
有味是清欢
6楼-- · 2019-01-01 06:26

I have a document like

enter image description here

I have to delete address from address array

After searching lots on internet I found the solution

Customer.findOneAndUpdate(query, {$pull: {address: addressId}}, function(err, data){
        if(err) {
          return res.status(500).json({'error' : 'error in deleting address'});
        }

        res.json(data);

      });
查看更多
登录 后发表回答