0

I have collection MyCollection which basically consists of its _id and a string called comment. This collection should be bulk-updatable.

That's done like this:

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

So far so good.

However, now the requirement is, that a commentHistory should be added which should look like [{"oldValue": "oldValueOfComment", "newValue": "newValueOfComment"}, ...]

I know I need to use $push for adding a new object to the commentHistory array. But how do I access the comment of the document updated right now, i.e. its current value?

I've tried

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

but to no avail. The string $comment is added hard-coded, instead of the field being accessed.

(Using Mongoose 5.12.10 and Mongo 4.4.18)

1 Answer 1

1

You need to use update with aggregate pipeline.

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
            }
          ]
        ]
      }
    }
  }
])

Demo

Sign up to request clarification or add additional context in comments.

2 Comments

Thansk! But do you happen to know how to do that in Mongoose? According to this answer and its comments things seem not that easy: stackoverflow.com/a/66922686/2710714
Oh, i thought you can simply replace your query with this. No, I don't know if this works with Mongoose.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.