0

I have this document in mongodb:

_id: "xxxx", "timestamp": ISODate("2022-03-26T10:33:47.738Z")

I would like to create a migration that will copy over timestamp to timestamp2 field. Something like this:

db.task.updateMany(
  { "timestamp2": { $exists: false } },
  { $set: { "timestamp2": $timestamp }}
)

So if document 1 have 2022-03-26T10:33:47.738Z as timestamp, its timestamp2 will be the same (2022-03-26T10:33:47.738Z). If document 2 have 2021-03-26T10:33:47.738Z as timestamp, its timestamp2 will be the same (2021-03-26T10:33:47.738Z) How can I achieve this? thanks

nanakondor
  • 615
  • 11
  • 25
  • Check out https://docs.mongodb.com/manual/reference/method/db.collection.updateMany/index.html#update-many-update, and note that `$set` is an alias of `$addFields` – Joe Mar 18 '21 at 16:03
  • @nanakondor did it solved for you? I have a very similar question https://stackoverflow.com/questions/68130570/how-to-add-a-new-nested-field-where-the-value-should-retrieve-from-existing-fiel – Abdul Hameed Jun 25 '21 at 12:06
  • 1
    @AbdulHameed yes it did. I got help from here https://developer.mongodb.com/community/forums/t/updatemany-in-mongodb-using-value-of-other-field/99555 and I will be posting the answer below – nanakondor Jun 26 '21 at 14:57

1 Answers1

1

This is what I end up using:

module.exports = {
async up(db, client) {
    await db.collection('task').updateMany(
      { timestamp2: { $exists: false }},
      [ { $set: { timestamp2: "$timestamp" } } ]
    )
  },

  async down(db, client) {
    // Not possible to rollback updateMany
  }
};
nanakondor
  • 615
  • 11
  • 25