我有一个名为 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() 函数。我对后端非常陌生。是否有 mongo 特定方法可以做到这一点?
我已经成功编写了一个如下所示的函数。
up(db, client) {
return db.collection('fruit-data')
}
最佳答案
尝试update with aggregation pipeline从 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 }
)
关于node.js - 使用 Mongo Migration 展平对象数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67197071/