【问题标题】:Flatten a object data using Mongo Migration使用 Mongo Migration 展平对象数据
【发布时间】:2021-07-15 17:17:50
【问题描述】:

我有一个名为 fruit-data.in 的 mongo 集合,我的文档看起来像这样。

{
  name:Apple,
  weight:100g,
  color:red,
  other_data:{
   havested_by:Jhone,
   havested_from:Rileys Farm,
   city: Oak Glen, California,
   country:USA
 }
}

我想删除嵌套对象并将该数据恢复到同一级别。使用 mongo 迁移。我正在使用migrate-mongo 库。

{
   name:Apple,
   weight:100g,
   color:red,
   havested_by:Jhone,
   havested_from:Rileys Farm,
   city: Oak Glen, California,
   country:USA
 }

我唯一知道的。我必须编写 up() 函数。我对后端很陌生。有 mongo 特定的方法吗?

我已经设法编写了一个看起来像这样的函数。

up(db, client) {
    return db.collection('fruit-data')
 }

【问题讨论】:

    标签: node.js mongodb mongoose nestjs


    【解决方案1】:

    从 MongoDB 4.2 开始尝试update with aggregation pipeline

    • 检查条件是否存在other_data 字段为真
    • 设置所有对象的字段并取消设置other_data对象
    db.collection('fruit-data').update(
      { other_data: { $exists: true } },
      [{
        $set: {
          havested_by: "$other_data.havested_by",
          havested_from: "$other_data.havested_from",
          city: "$other_data.city",
          country: "$other_data.country"
        }
      },
      {
        $unset: "other_data"
      }],
      { multi: true }
    )
    

    Playground


    没有硬编码属性的第二个选项,

    • $mergeObjects 将根文档与other_data 的字段合并
    • $replaceRoot 将上面的合并对象替换为根
    • 取消设置other_data对象
    db.collection('fruit-data').update(
      { other_data: { $exists: true } },
      [{
        $replaceRoot: {
          newRoot: {
            $mergeObjects: ["$$ROOT", "$other_data"]
          }
        }
      },
      {
        $unset: "other_data"
      }],
      { multi: true }
    )
    

    Playground

    【讨论】:

    • 有什么方法可以获取 other_data 对象中的所有数据。无需硬编码属性名称。因为我实际的 other_data 对象有 20 个属性。
    猜你喜欢
    • 2019-12-17
    • 2020-09-05
    • 2017-06-13
    • 2021-12-25
    • 2019-12-04
    • 2014-06-23
    • 1970-01-01
    • 2021-07-04
    • 2018-02-24
    相关资源
    最近更新 更多