有没有办法在不使用循环的情况下更新多个文档以将特定数字添加到一列

Is there a way to update multiple documents to add certain number to one column without using loops

本文关键字:数字 添加 一列 文档 循环 更新 情况下 有没有      更新时间:2023-09-26

我正在使用SailsJS和MongoDB,并有一个这样的模型:

module.exports = {
   attributes: {
       name : { type: 'string' },
       openDate: { type: 'date' },
 }
}

数据库中有数百个文档。现在我有一个带有名称列表的数组。并且需要向名称为列表的打开日期添加 30 天。有没有办法在不创建循环的情况下做到这一点,并且在循环中获取名称并逐个更新 openDate,但使用 一个 collections.update 来实现这一点?目前,我只有代码来查找名称在列表中的所有文档,但不确定下一步该怎么做。

Accounts.find({
            name:{ $in : nameList}
        }).exec(function(err, data) {

});

除非您可以将相同的日期应用于所有记录(我认为这不是您想要的(,否则答案是否定的。没有机制可以做到这一点,但它应该是(你或某人应该在他们的 github 存储库上提出它(,至少将一个 id 数组传递给条件和一个匹配的值数组作为更新的第二个参数,并且根据文档你可以传递一个值数组, 但是我已经测试过它,它抛出了一个错误(至少在 mysql 适配器上(,并且没有测试来备份该功能。

所有示例都使用 lodashes6 箭头函数,并假设您有一个 fn 来增加日期(

因此,如果可以使用相同的值,则可以执行以下操作:

Accounts.find({name:{ $in : nameList}}).exec(function(err, data) {
  // error handling here
  var criteria = _.map(data, 'id'); // same as pluck
  Accounst.update(criteria,  {openDate: increaseDate(x.openDate)}).exec(...);
});

猜测上述不是一个选项,您需要使用异步系列或并行之类的东西,如下所示:

Accounts.find({name:{ $in : nameList}}).exec(function(err, records) {
      // error handling here
      tasks = _.map(records, (x)=> Accounts.update(x.id, {openDate: increaseDate(x.openDate)}, callback));
      async.parallel(tasks, function(err, results){});
    });

就我而言,我使用 async/await,所以这样做很重要,更新将按顺序运行:

  async(()=> {
    records = await (Accounts.find({name:{ $in : nameList}});
    _.each(records, (x)=> await (Accounts.update(x.id, {openDate: increaseDate(x.openDate)}));
  })()

或者并行运行它们,像这样

  async(()=> {
    records = await (Accounts.find({name:{ $in : nameList}});
    tasks = _.map(records, (x)=> Accounts.update(x.id, {openDate: increaseDate(x.openDate)}));
    await (tasks)
  })()