Mongoose Delete Many by Id

Introduction

The deleteMany() method is one of the most popular methods in mongoose to delete documents from a MongoDB collection. It is a very simple method. All we have to do is, just pass a query that contains condition(s) and the documents get deleted. But suppose we want to delete multiple documents by the value of their id field. Then what? The id field is unique for each document in a collection. Then how can the deleteMany() method delete multiple documents? There is a way to do this. In this article, we will discuss how to use Mongoose to delete many by the id field.

We will use the details collection.

{ "_id" : ObjectId("5dc4705254a67437ca1aafb0"), "name" : "John" }
{ "_id" : ObjectId("5dc4705554a67437ca1aafb1"), "name" : "Sam" }
{ "_id" : ObjectId("5dc4705854a67437ca1aafb2"), "name" : "Max" }
{ "_id" : ObjectId("5dc4705b54a67437ca1aafb3"), "name" : "Lisa" }
{ "_id" : ObjectId("5dc4705e54a67437ca1aafb4"), "name" : "Rose" }

We can notice that the value of the _id field is unique in each document.

For performing HTTP endpoint testing, we will use the postman tool. You can download the postman tool from www.getpostman.com.

$in operator

Before we move further, we need to understand the $in operator. To accomplish the task, we have to use $in operator. When we use the $in operator, we specify an array and during the matching process, any value in the array can match. Not all the values need to match. For example, we want to match any of these three colors – red, yellow and green. We can use the $in operator in the following way.

{
  color: {
    $in: ["red", "yellow", "green"];
  }
}

If we pass this as the query to the deleteMany() method, it will match all the documents where the color is either red, yellow or green. In the same way, we will use the $in operator to delete multiple documents by id.

deleteMany() by id

The following route handler will be invoked when the endpoint ‘/delete’ will be executed.

router.route("/delete").delete(function(req, res) {});

Let’s insert the deleteMany() method.

details.deleteMany({}, function(err, result) {
  if (err) {
    res.send(err);
  } else {
    res.send(result);
  }
});

Currently, there is just an empty object passed as the query. Let’s use the $in operator to delete documents where the values of _id field are – 5dc4705254a67437ca1aafb0, 5dc4705554a67437ca1aafb1, and 5dc4705854a67437ca1aafb2. These are the first three documents in details collection.

{
  _id: {
    $in: [
      "5dc4705254a67437ca1aafb0",
      "5dc4705554a67437ca1aafb1",
      "5dc4705854a67437ca1aafb2"
    ];
  }
}

This is how the query will look. Let’s insert it in the deleteMany() methods.

router.route("/delete").delete(function(req, res) {
  details.deleteMany(
    {
      _id: {
        $in: [
          "5dc4705254a67437ca1aafb0",
          "5dc4705554a67437ca1aafb1",
          "5dc4705854a67437ca1aafb2"
        ]
      }
    },
    function(err, result) {
      if (err) {
        res.send(err);
      } else {
        res.send(result);
      }
    }
  );
});

Let’s execute this route using the postman tool and see what happens.

The deleteMany() method returns an object.

  1. n – number of matched documents
  2. ok – 1 if the operation was successful
  3. deletedCount – number of deleted documents

So, in our result, the value of n is 3 (as we expected because we specified three values in the array), this means the query matched three documents. The value of deletedCount is also 3, this means all the matched documents were deleted successfully. Let’s verify using the mongo shell.

> db.details.find()
{ "_id" : ObjectId("5dc4705b54a67437ca1aafb3"), "name" : "Lisa" }
{ "_id" : ObjectId("5dc4705e54a67437ca1aafb4"), "name" : "Rose" }
>

Yes! The first three documents are deleted.

Conclusion

The deleteMany() method is very useful. Using it will the $in operator is very efficient. Although the values of _id are unique for each document in a collection but using the deleteMany() method with the $in operator makes it possible to delete multiple documents by id.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.