node.js - 使用 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')
}
解决方案
尝试从 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 }
)
推荐阅读
- java - SpringBoot如何开启History模式
- java - 在 Tomcat 中调试 Vaadin 14
- python - 将 JSON 请求转换为数据框中的一行
- javascript - 属性 X 在 App 类型上不存在
- flutter - 我有这个问题谁能告诉我如何解决它?
- r - rstanarm - 运行贝叶斯模型时出错
- javascript - 将组件状态传递给 next.js 中应用程序的所有组件的 Props 替代方法
- javascript - React bootstrap navbar 不会显示在 1 行
- sql - 如何将一系列存储过程合并到一个更大的存储过程中
- html - min-height 父级的子元素不尊重父级的 100% 高度