获取Mongoose UpdateMany受影响文档的计数

tyky79it  于 2023-01-26  发布在  Go
关注(0)|答案(2)|浏览(132)

假设我们有代码:

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

如何获得受影响文档的数量(计数)?

9vw9lbht

9vw9lbht1#

如文档中所述,您可以在响应的nModified字段中获得更新文档的数量。
所以你可以这样访问它:

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);
utugiqy6

utugiqy62#

如果您使用的是MongoDB版本〉= 5.0,则使用modifiedCount代替nModified
例如

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);

相关问题