【问题标题】:Sorting records and then using updateMany in MongoDB with limit对记录进行排序,然后在 MongoDB 中使用 updateMany 限制
【发布时间】:2019-03-22 15:18:20
【问题描述】:

我正在尝试更新我的 MongoDB 数据库中的所有记录。我想根据日期(updatedAt)按升序对记录进行排序。然后根据其当前状态(currentStatus)更新有限数量的记录。

字段是这样的:

我试过了,但没有用:

var count = 20;
var sortUpdatedAt = this.collection.find({}).sort({"updatedAt":1});
try {
    this.collection.updateMany(sortUpdatedAt,
     {"currentStatus": {$in:["ACTIVE","IDLE"]} },
     { $set: { "currentStatus" : "SHUTDOWN" } }
    ).limit(count);
} catch (e) {
    logger.error(e);
}

创建变量 sortUpdatedAt 因为我读到 updateMany 不支持 .sort()

【问题讨论】:

    标签: javascript node.js mongodb nosql


    【解决方案1】:

    很遗憾,findupdateMany 不是这项工作的正确工具。相反,您应该查看aggregation pipeline。通过$sort$filter$limit 聚合运算符的组合,您应该能够执行问题中描述的确切操作。

    PS:不要忘记为您正在排序的字段添加索引(如果您还没有),以提高性能,如果这是您的集合的常用操作。

    【讨论】:

      【解决方案2】:

      您可以找到最后一个可接受的updatedAt,并将其用作更新查询中的参数:

      // done inside async context
      var count = 20;
      var lastAcceptable = await this.collection
        .find({
          currentStatus: { $in: ["ACTIVE", "IDLE"] }
        })
        .sort({ updatedAt: 1 })
        .limit(count);
      var lastElement = lastAcceptable.pop();
      try {
        this.collection.updateMany(
          {
            currentStatus: { $in: ["ACTIVE", "IDLE"] },
            updatedAt: { $lte: lastElement.updatedAt }
          },
          { $set: { currentStatus: "SHUTDOWN" } }
        );
      } catch (e) {
        logger.error(e);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-14
        • 1970-01-01
        • 1970-01-01
        • 2015-07-29
        • 2013-03-29
        • 2016-07-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多