使用Mongo迁移来展平对象数据



我有一个名为fruit-data的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(db, client) {
return db.collection('fruit-data')
}

尝试从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的字段合并
  • $replaceRoot将上述合并对象替换为根
  • 取消设置other_data对象
db.collection('fruit-data').update(
{ other_data: { $exists: true } },
[{
$replaceRoot: {
newRoot: {
$mergeObjects: ["$$ROOT", "$other_data"]
}
}
},
{
$unset: "other_data"
}],
{ multi: true }
)

游乐场

最新更新