简体   繁体   中英

UpdateMany in mongodb using value of other field

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

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
  }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM