Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose - remove multiple documents in one function call

In documentation there's deleteMany() method

Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }, function (err) {}); 

I want to remove multiple documents that have one common property and the other property vary. Something like this:

Site.deleteMany({ userUID: uid, id: [10, 2, 3, 5]}, function(err) {}

What would be the proper syntax for this?

like image 973
Maciej Krawczyk Avatar asked Jun 09 '17 22:06

Maciej Krawczyk


People also ask

What does deleteMany return in Mongoose?

deleteMany works in Mongo: Returns: A document containing: A boolean acknowledged as true if the operation ran with write concern or false if write concern was disabled. deletedCount containing the number of deleted documents.

What does findByIdAndDelete return?

The findByIdAndDelete() is a function in Mongoose used to find a document by the _id field and then remove the document from the collection. It returns the document removed or deleted.

How can you query all documents in a collection with Mongoosejs?

find(filter); It will search for all the documents that match with the filter Object. But when you pass an empty filter, it will match with all the documents and will return all documents. This is how you can get all documents in Mongoose by using the mongoose find() function.


1 Answers

I believe what youre looking for is the $in operator:

Site.deleteMany({ userUID: uid, id: { $in: [10, 2, 3, 5]}}, function(err) {}) 

Documentation here: https://docs.mongodb.com/manual/reference/operator/query/in/

like image 96
Kevin Avatar answered Oct 02 '22 04:10

Kevin