【问题标题】:UpdateMany in mongodb using value of other fieldmongodb中的UpdateMany使用其他字段的值
【发布时间】:2021-06-26 22:58:41
【问题描述】:

我在 mongodb 中有这个文档:

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

我想创建一个迁移,将时间戳复制到 timestamp2 字段。像这样的:

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

因此,如果文档 1 的时间戳为 2022-03-26T10:33:47.738Z,则其时间戳 2 将相同 (2022-03-26T10:33:47.738Z)。如果文档 2 的时间戳为 2021-03-26T10:33:47.738Z,则其时间戳 2 将相同 (2021-03-26T10:33:47.738Z) 我怎样才能做到这一点?谢谢

【问题讨论】:

标签: mongodb migration migrate-mongo


【解决方案1】:

这就是我最终使用的:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-02
    • 2023-03-18
    • 2020-05-06
    • 2021-12-23
    • 2021-05-26
    相关资源
    最近更新 更多