JAN
JAN

Reputation: 21885

Get count of affected documents of Mongoose UpdateMany

Suppose we have the code :

 await Employees.updateMany(
        {
          InsertDate: {
            $gte: _yesterday,  // date ojbect that is passed as a param
            $lte: _today  // date ojbect that is passed as a param
          }
        },
        { $set: { RegistrationDate: ... // some var that I generate } }
      );

How can we get the number of affected documents (count) ?

Upvotes: 0

Views: 932

Answers (2)

Het Thummar
Het Thummar

Reputation: 51

If you are using MongoDB version >= 5.0 then use modifiedCount instead of nModified

For example

const response = await Employees.updateMany(
  {
    InsertDate: {
      $gte: _yesterday,  // date ojbect that is passed as a param
      $lte: _today  // date ojbect that is passed as a param
    }
  },
  { $set: { RegistrationDate: ... // some var that I generate } }
);

console.log("Number of updated documents: ", response.modifiedCount);

Upvotes: 0

SuleymanSah
SuleymanSah

Reputation: 17888

As documented in the docs, you can get the number of updated documents in the response's nModified field.

So you can access it like this:

const response = await Employees.updateMany(
  {
    InsertDate: {
      $gte: _yesterday,  // date ojbect that is passed as a param
      $lte: _today  // date ojbect that is passed as a param
    }
  },
  { $set: { RegistrationDate: ... // some var that I generate } }
);

console.log("Number of updated documents: ", response.nModified);

Upvotes: 2

Related Questions