簡體   English   中英

MongoDB:通過 $push 向數組添加元素時訪問文檔的當前值

[英]MongoDB: Access current value of document when adding element to array via $push

我有一個集合MyCollection ,它基本上由它的_id和一個名為comment的字符串組成。 該集合應該是可批量更新的。

這樣做是這樣的:

   for (const obj of inputObjects) {
      bulkObjectsToWrite.push({
        updateOne: {
          filter: { _id: obj._id },
          update: {
            $set: {
              comment: obj.comment
            }
          }
        }
      })
    }
    await MyCollection.bulkWrite(bulkObjectsToWrite)

到目前為止,一切都很好。

但是,現在的要求是,應該添加一個commentHistory ,它應該看起來像[{"oldValue": "oldValueOfComment", "newValue": "newValueOfComment"}, ...]

我知道我需要使用$push將新的 object 添加到commentHistory數組。 但是我如何訪問當前更新的文檔的comment ,即它的當前值?

我試過了

$push: {
              commentHistory: {
                newValue: obj.comment,
                oldValue: '$comment',
              },
},

但無濟於事。 字符串$comment被硬編碼添加,而不是被訪問的字段。

(使用 Mongoose 5.12.10 和 Mongo 4.4.18)

您需要將更新與聚合管道一起使用。

db.collection.update({
  "key": 1
},
[
  {
    $set: {
      "comment": "New",
      "commentHistory": {
        "$concatArrays": [    //concatenate existing history array with new array entry
          "$commentHistory",
          [
            {
              "newValue": "New",
              "oldValue": "$comment"  //referencing the existing value
            }
          ]
        ]
      }
    }
  }
])

演示

暫無
暫無

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

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