如何解决通过数组映射时将值解析为字段
在mongoDB聚合框架中,我试图通过数组映射时将值解析为字段-但到目前为止还算没有运气,即mongoplayground example。任何指针都是受欢迎的,因为我能想到的唯一其他选择是两次查询数据库,这似乎很浪费。链接中的预期结果:
[
{
"_id": ObjectId("5a934e000102030405000000"),"myField2_e": "field_a1","routesArr_e": [
{
"field_a1": 8197,"field_a2": "a string","field_b": "b string","field_c": 8197
},{
"field_a1": 8198,"field_a2": "aa string","field_b": "bb string","field_c": 8198
}
]
}
]
解决方法
您可以使用$reduce
和$objectToArray
转换数组中的对象,并使用$cond
检查条件是否与myField_e
匹配,否则返回空白,
db.collection.aggregate([
{
$project: {
myField2_e: "$myField_e",routesArr_e: {
$map: {
input: "$mainField_e.routesArr_e",in: {
"field_a1": "$$this.eField_a.field_a1","field_a2": "$$this.eField_a.field_a2","field_b": "$$this.field_b","field_c": {
$reduce: {
input: { $objectToArray: "$$this.eField_a" },initialValue: "",in: {
$cond: [{ $eq: ["$$this.k","$myField_e"] },"$$this.v","$$value"]
}
}
}
}
}
}
}
}
])
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。