How to remove array element in mongodb?

150

Here is array structure

contact: {
    phone: [
        {
            number: "+1786543589455",
            place: "New Jersey",
            createdAt: ""
        }
        {
            number: "+1986543589455",
            place: "Houston",
            createdAt: ""
        }

    ]
}

Here I only know the mongo id(_id) and phone number(+1786543589455) and I need to remove that whole corresponding array element from document. i.e zero indexed element in phone array is matched with phone number and need to remove the corresponding array element.

contact: {
    phone: [
        {
            number: "+1986543589455",
            place: "Houston",
            createdAt: ""
        }
    ]
}

I tried with following update method

collection.update(
    { _id: id, 'contact.phone': '+1786543589455' },
    { $unset: { 'contact.phone.$.number': '+1786543589455'} }
);

But it removes number: +1786543589455 from inner array object, not zero indexed element in phone array. Tried with pull also without a success.

How to remove the array element in mongodb?

This question is tagged with mongodb

~ Asked on 2013-06-06 09:58:19

The Best Answer is


260

Try the following query:

collection.update(
  { _id: id },
  { $pull: { 'contact.phone': { number: '+1786543589455' } } }
);

It will find document with the given _id and remove the phone +1786543589455 from its contact.phone array.

You can use $unset to unset the value in the array (set it to null), but not to remove it completely.

~ Answered on 2013-06-06 10:25:10


18

This below code will remove the complete object element from the array, where the phone number is '+1786543589455'

db.collection.update(
  { _id: id },
  { $pull: { 'contact': { number: '+1786543589455' } } }
);

~ Answered on 2017-03-23 10:18:12


Most Viewed Questions: