Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete many documents from collection in MongoDB by _id in NodeJs [duplicate]

I have an array of _ids, like, for example

["a12s", "33qq", "121a"]

I know, there are two method in MongoDB like deleteMany, where I can delete by specific query

  var myquery = { address: 'abc' };
  dbo.collection("customers").deleteMany(myquery, function(err, obj) {
    if (err) throw err;
  });

and deleteOne, where I could delete one specific chosen document.

I would like to delete the documents with the ids from a given array, but can't find anywhere in documentation something about this. Is it possible in MongoDB?

like image 758
Anna F Avatar asked May 30 '18 20:05

Anna F


People also ask

How do I delete multiple files in MongoDB Nodejs?

You can delete multiple documents in a collection at once using the collection. deleteMany() method. Pass a query document to the deleteMany() method to specify a subset of documents in the collection to delete.

How do I remove all files from a collection in MongoDB?

To delete all documents in a collection, pass an empty document ( {} ). Optional. To limit the deletion to just one document, set to true . Omit to use the default value of false and delete all documents matching the deletion criteria.

What is the fastest operation to clear an entire collection in MongoDB?

drop() will delete to whole collection (very fast) and all indexes on the collection.


1 Answers

You are looking for the $in operator. It matches values in an array. You can use it in the deleteMany method filter parameter.

var ids = ["a12s", "33qq", "121a"];
var myquery = { _id: { $in: ids } };
  dbo.collection("customers").deleteMany(myquery, function(err, obj) {
    if (err) throw err;
  });
like image 90
Boric Avatar answered Sep 18 '22 10:09

Boric