MongoDB, remove object from array
Asked Answered
T

8

130

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.

Tiga answered 26/3, 2013 at 15:51 Comment(1)
Have you tried this? #9048924Gardner
J
212

try..

db.mycollection.update(
    { '_id': ObjectId("5150a1199fac0e6910000002") }, 
    { $pull: { items: { id: 23 } } },
    false, // Upsert
    true, // Multi
);
Journalistic answered 26/3, 2013 at 16:9 Comment(3)
yup, my syntax was wrong. Thanks! Also tried without the upset and multi options and that worked as well.Tiga
What are those boolean values?Ommatophore
@NicolasDelValle if I remember correctly, these were options upsert and multi. For current syntax & documentation check this link: docs.mongodb.com/manual/reference/method/db.collection.updateYamen
B
13

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} }, (err, data) => {
    if (err) {
        return res.status(500).json({ error: 'error in deleting address' });
    }

    res.json(data);
});
Benumb answered 23/7, 2015 at 10:23 Comment(2)
How to do this in MongoDB CLI ?Casaba
I think this is nodejs (express) solution not the MongoDB query solutionGernhard
I
8

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 }
  ]
}
Inceptive answered 18/10, 2016 at 11:43 Comment(0)
S
6

You can try it also:

db.getCollection('docs').update({ },{'$pull':{ 'items':{'id': 3 }}},{multi:true})
Skirl answered 23/3, 2018 at 6:1 Comment(0)
K
6

For a single record in array:

db.getCollection('documents').update(
    { },
    {'$pull':{ 'items':{'mobile': 1234567890 }}},
    {new:true}
);

For a multiple records with same mobile number in array:

db.getCollection('documents').update(
    { },
    {
        $pull: {
            items: { mobile: 1234567890 }
        }
    },
    { new:true, multi:true }
)
Kalli answered 1/5, 2020 at 9:25 Comment(0)
D
1

Use $pull to remove the data

return this.mobiledashboardModel
.update({"_id": args.dashboardId}, { $pull: {"viewData": { "_id": widgetId}}})
.exec()
.then(dashboardDoc => {
     return {
        result: dashboardDoc
     }
});
Dzoba answered 3/2, 2017 at 12:14 Comment(0)
M
0

Kishore Diyyana:

If you want to remove all elements including the key of the element attributes list.

Here is the example of mongoDB unset operator:

db.UM_PREAUTH_CASE.update(
{ 'Id' : 123}, { $unset: { dataElements: ""} } )

JSON Look like this:

{ "Id":123,"dataElements" : [ { "createdBy" : "Kishore Babu Diyyana", "createdByUserId" : 2020 }, { "createdBy" : "Diyyana Kishore", "createdByUserId" : 2021 } ] }
Mingle answered 27/10, 2020 at 16:5 Comment(0)
M
0
Very simple way to do this:-

Sample data that I used is:-
{
            "_id": "6419606109433f61b50dfaa4",
            "category": "SUV",
            "vehicles": [
                {
                    "id": "18d527aa-948e-40bc-9ce1-c54dc04a6350"
                    "name": "Honda City 4th Generation",
                    "average": "23.26 kmpl",
                    "cc": "1197 cc",
                    "seat": "5 Seater",
                },
{
                    "id": "18d527aa-948e-40bc-9ce1-c54dc04a6349"
                    "name": "Honda City 4th Generation",
                    "average": "23.26 kmpl",
                    "cc": "1197 cc",
                    "seat": "5 Seater",
                },
}

exports.delete_vehicle = async (req, res, next) => {
  const { id, vuuid } = req.params;
  const vehicle = await VehicleCategory.find({ _id: id });
  try{
    for(let i = 0; i < vehicle[0].vehicles.length; i++){
      if(vehicle[0].vehicles[i].id === vuuid){
        await VehicleCategory.findByIdAndUpdate(
          {_id:id},
          { $pull: { vehicles: { id: vuuid } } },
          { new: true }
        );
        res.status(200).json({
          message: "Vehicle deleted successfully."
        });
      }else{
        res.status(404).json({
          message: "The given id is not found."
        });
      }
    }
  }catch (err) {
    res.status(500).json({
      error: err
    });
  }
  

};

router.put("/deleteVehicle/:id/:vuuid", userController.delete_vehicle);

Medullated answered 23/3, 2023 at 9:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.