Delete whole document for matching objectId in array of objects - MongoDB

Viewed 288

The structure of my document looks like this in MongoDB :-

{
_id : "7464bbuiecdhbjdje"
client : "MJMK"
users : [
   {_id : "1234" , name : "first user"} 
 ]
}

I would like to remove the whole document for matching users._id. In this case, for a user with _id 1234,the whole document needs to be removed. I have been unable to find any efficient function that does this in Node using mongoose. Thanks for your help.

3 Answers

You want to use deleteMany.

This will delete all documents containing the matches query, in this case a user with matching _id in the users array. Our query will be utilizing Mongo's dot notation to access the array like so:

Model.deleteMany({ 'users._id': "1234" })

Try this: db.collectionName.remove({"users._id":{_id:"1234"}})

From the shell following works. Isn't it possible to do the same in node?

db.collectionname.find({ "users": { $elemMatch: { "_id": "1234" } } })
db.collectionname.remove({ "users": { $elemMatch: { "_id": "1234" } } })
Related