2

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.

2
  • Have you tried Model.deleteOne({ 'users._id': "1234" }) (where Model is the variable representing your mongoose model )? Make sure that your _id has the correct type as you defined in the schema Commented Jul 8, 2020 at 10:16
  • What exactly is the structure of users? Is that a list of objects? Does each object have an _id entry in it? Commented Jul 12, 2020 at 10:08

3 Answers 3

1
+50

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" })
Sign up to request clarification or add additional context in comments.

Comments

0

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" } } })

Comments

0

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

2 Comments

What if it is not guaranteed that users has exactly one element in the array?
check it out: db.collectionName.remove({"users._id":{_id:"1234"}})

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.