mongodb - MongoDB使用聚合连接两个字段,其中实际字段位于数组中
问题描述
我有一个如下所示的 mongo 文档;
{
"_id" : "123",
"info" : {
"batch" : "Batch1-Minor"
},
"batchElements" : {
"elements" : [
{
"_id" : "elementId1",
"type": "ABC"
},
{
"_id" : "elementId2",
"type": "ABC"
}
]
}
}
如何通过连接和更改_id
内部字段来生成聚合输出elements
$info.batch
$batchElements.elements._id
预期输出:
{
"_id" : "123",
"info" : {
"batch" : "Batch1-Minor"
},
"batchElements" : {
"elements" : [
{
"_id" : "Batch1-Minor-elementId1",
"type": "ABC"
},
{
"_id" : "Batch1-Minor-elementId2",
"type": "ABC"
}
]
}
}
解决方案
通过下面的查询,我们正在迭代& 用& batchElements.elements
& 形成对象,最后会将对象数组推回将字段添加到实际文档的位置,试试这个:type
_id
$map
batchElements.elements
$addFields
db.yourCollectionName.aggregate([{
$addFields: {
'batchElements.elements': {
$map:
{
input: "$batchElements.elements",
as: "each",
in: { type: '$$each.type', '_id': { $concat: ["$info.batch", "-", "$$each._id"] } }
/** So if you've multiple fields in each object then instead of listing all, You need to use
in: { $mergeObjects: ["$$each", { '_id': { $concat: ["$info.batch", "-", "$$each._id"] } }] } */
}
}
}
}])
推荐阅读
- python - 如何传递一个在 URL 中可见的参数和一个在 Django 中不可见的参数?
- excel - 对值求和,直到达到某个值,然后从下一列开始
- python - TensorFlow 不使用 GPU
- .htaccess - Varnish Cache 是否会阻止 .conf 文件规则?(例如:网页之间的重定向)
- html - 如何使用 fullpage.js 在移动设备上从 3 张幻灯片制作 9 张幻灯片?
- swift - 在 swift 4 或更高版本上创建触摸测试应用程序
- reactjs - 如何使用 React PWA 像原生 iOS 应用一样进行导航转换?
- java - 没有 web.xml 的 JNDI 参考和查找资源
- javascript - 扩展 ng2-pdf-viewer 以支持在 pdf 之上绘图的方法?
- java - 如何使用 Jackson 和 spring-boot 将简单的 Kotlin 数据类映射到/从 json