[英]Retrieve value from array of objects
I have a mongo db record like this我有这样的 mongo db 记录
items: [
0: {
key: name,
value: y
},
1: {
key: module,
value: z
}
]
And per record my expected output is this根据记录,我预期的 output 是这个
{
name : y,
module : z
}
What is the best mongo db aggregation i should apply to achieve this.我应该应用什么最好的 mongo db 聚合来实现这一点。 I have tried few ways but i am unable to produce output.我尝试了几种方法,但无法生产 output。 We can't use unwind otherwise it will break the relationship between name and module.我们不能使用 unwind 否则会破坏名称和模块之间的关系。
Query询问
document {}
items 数组几乎可以成为document {}
$map
to rename key->k
and value->v
(those are the field names mongo needs) $map
重命名key->k
和value->v
(这些是 mongo 需要的字段名称)$arrayToObject
to make the items [] => {} $arrayToObject
使项目 [] => {}items {}
(we don't need it anymore the fields are part of the root document now)并投影items {}
(我们不再需要它,这些字段现在是根文档的一部分) *you can combine the 2 $set
in 1 stage, i wrote it in 2 to be simpler *你可以在 1 阶段结合 2 $set
,我在 2 中写它更简单
aggregate(
[{"$set":
{"items":
{"$map":
{"input": "$items", "in": {"k": "$$this.key", "v": "$$this.value"}}}}},
{"$set": {"items": {"$arrayToObject": ["$items"]}}},
{"$replaceRoot": {"newRoot": {"$mergeObjects": ["$items", "$$ROOT"]}}},
{"$project": {"items": 0}}])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.