簡體   English   中英

mongoose 更新文檔同時聚合

[英]mongoose update document while aggregating

我有一個名為room的集合,其中包含一組名為potArr的花盆。 我的房間還有一個名為 average pot 的屬性,它應該等於 potArr 中potAmount值的potArr 我想不斷更新平均底池。 這是我的代碼:

const rooms = await roomModel.find({});
for (let room of rooms) {
  let sumOfPots = 0;
  room.potArr.forEach((pot) => {
    sumOfPots += pot.potAmount;
  };
  await roomModel.update({_id : room._id}, {$set : {averagePot: sumOfPots/room.pot.length}});
}

我希望能夠使用 mongoose updateMany用一行來總結上述代碼。 我怎樣才能做到這一點?

像這樣做:

await roomModel.collection.updateMany({}, [{$set: {averagePot: {$toInt: {$avg: '$potArr.pot'}}}}]);
  • 您必須在.collection上使用 .collection 以使mongoose的行為類似於mongod

  • 我使用$toInt來舍入可能的浮動結果。 您可以跳過該部分,如下所示。

await roomModel.collection.updateMany({}, [{$set: {averagePot: {$avg: '$potArr.pot'}}}]);

暫無
暫無

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

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