11

This is my first web application and I need to delete a nested array item. How would you delete an object in Mongoose with this schema:

User: {
    event: [{_id:12345, title: "this"},{_id:12346, title:"that"}]
}

How can I go about deleting id:12346 in mongoose/Mongo?

3 Answers 3

17

Use $pull to remove items from an array of items like below :

db.User.update(
  { },
  { $pull: { event: { _id: 12346 } } }
)

The $pull operator removes from an existing array all instances of a value or values that match a specified condition.

Empty object in the first parameter is the query to find the documents. The above method removes the items with _id: 12345 in the event array in all the documents in the collection. If there are multiple items in the array that would match the condition, set multi option to true as shown below :

db.User.update(
  { },
  { $pull: { event: { _id: 12346 } } },
  { multi: true}
)
Sign up to request clarification or add additional context in comments.

5 Comments

If I am reading this right it will search everything for event { _id: 123456) and remove it, correct? If needed I can just remove one instance by putting an ID in the first condition, correct?
It'll remove all the items with _id:123456 from the array event in all the documents in the collection User. If you want to remove all the matching documents, you can just use remove method
$pull will delete specific value/values in an existing array and not the whole document that matches the condition. If you want to delete the whole document that matches the condition, use db.collection.remove
4yrs later this is still the correct answer. Thanks @Supradeep!
@Supradeep what if i want to remove multiple nested objects by their ids??
1

Findone will search for id,if not found then err otherwise remove will work.

   User.findOne({id:12346}, function (err, User) {
        if (err) {
            return;
        }
        User.remove(function (err) {
            // if no error, your model is removed
        });
    });

Comments

1
User.findOneAndUpdate({ _id: "12346" }, { $pull: { event: { _id: "12346" } } }, { new: true });

1 Comment

Why is it not a good solution?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.