[英]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()
您可以找到最后一個可接受的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.