简体   繁体   English

mongodb 中的 UpdateMany 使用其他字段的值

[英]UpdateMany in mongodb using value of other field

I have this document in mongodb:我在 mongodb 中有这个文件:

_id: "xxxx", "timestamp": ISODate("2022-03-26T10:33:47.738Z") _id:“xxxx”,“时间戳”:ISODate(“2022-03-26T10:33:47.738Z”)

I would like to create a migration that will copy over timestamp to timestamp2 field.我想创建一个迁移,将时间戳复制到 timestamp2 字段。 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).因此,如果文档 1 的时间戳为 2022-03-26T10:33:47.738Z,则其时间戳 2 将相同(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?如果文档 2 有 2021-03-26T10:33:47.738Z 作为时间戳,它的时间戳 2 将是相同的 (2021-03-26T10:33:47.738Z) 我该如何实现? 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
  }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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