簡體   English   中英

排序記錄,然后在MongoDB中使用帶有限制的updateMany

[英]Sorting records and then using updateMany in MongoDB with limit

我正在嘗試更新MongoDB數據庫中的所有記錄。 我想基於日期以升序對記錄進行排序。 然后根據其當前狀態(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()

不幸的是, findupdateMany不是這項工作的正確工具。 相反,您應該查看聚合管道 通過結合使用$sort$filter$limit聚合運算符,您應該能夠執行問題中所述的確切操作。

PS:如果要對集合進行通用操作,請不要在要排序的字段(如果尚未添加)上添加索引以提高性能。

您可以找到最后一個可接受的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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM