首页 > 解决方案 > 使用 Mongo Migration 展平对象数据

问题描述

我有一个名为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.jsmongodbmongoosenestjs

解决方案


尝试从 MongoDB 4.2 开始使用聚合管道进行更新,

  • other_data如果字段存在则检查条件true
  • 设置所有对象的字段并取消设置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 }
)

操场


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

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

操场


推荐阅读