MongoDB 批量删除和更新保留文档

时间:2021-01-21 12:33:28

标签: mongodb

我想删除旧通知,但可能存在客户端代码尝试更新它,然后批处理不再删除它的情况。假设我有:

const notifications = [{
    "_id": new BSON.ObjectId("5f9c4343b698fd2aa9a7f2c4"),
    date: 1610738368555,
    title: "keep 1",
},{
    "_id": new BSON.ObjectId("60096b8a701649487673c2c9"),
    date: 1611238361122,
    title: "keep 2",
}, {
    "_id": new BSON.ObjectId("60096bc5701649487673c2ca"),
    date: 1610638361122,
    title: "remove 1",
}, {
    "_id": new BSON.ObjectId("60096bc5701649487673c2ca"),
    date: 1610238361122,
    title: "remove 2",
}];

给定以下代码:

updateNotifications: notifications => {
    const bulk = _mongodb.collection("notifications").initializeUnorderedBulkOp();
    for (let { _id, ...updates } of notifications) {
        bulk
          .find({ _id })
          .upsert()
          .update({ $set: updates });
    }
    bulk
      .find({ date: { $lt: now() - MAX_NOTIFICATION_AGE } })
      .remove();
    return bulk.execute();
},

和输入:

updateNotifications([{
        "_id": new BSON.ObjectId("5f9c4343b698fd2aa9a7f2c4"),
        date: 1612238368555,
        title: "keep 1 modified",
    },{
        "_id": new BSON.ObjectId("60096bc5701649487673c2ca"),
        date: 1612238368555,
        title: "remove 1 modified",
    }, {
        "_id": new BSON.ObjectId("60096bc5701649487673c2cb"),
        date: 1612238368555,
        title: "new 1",
}])

我希望批量操作删除所有“remove %”条目,但由于其中一个在 for 循环中被修改,它不再被删除。你如何解决这个问题?

0 个答案:

没有答案