[英]Passing a value from one part of the MongoDB aggregation to another to sort the results
[英]Passing a value in MongoDB aggregation
可以说我有以下部分文件
{
"groups": [
{
"color": "Red",
"key": 1,
},
{
"color": "Blue",
"key": 2,
},
{
"color": "Yellow",
"key": 3,
},
"members": [
{
"name": "Deen",
"groupKey": 1,
},
{
"name": "Joe",
"groupKey": 2,
},
{
"name": "Michel",
"groupKey": 1,
},
{
"name": "Simon",
"groupKey": 3,
},
]
}
我想根据组颜色获得匹配的成员。 例如,对于红色,我将获得Deen和Michel,对于蓝色,我将获得Joe,对于黄色,我将获得Simon。
可以一次汇总执行此操作吗? 我需要通过查询其颜色来获取组密钥,然后从那里通过查询groupKey来获取成员。
您可以尝试下面3.4中的汇总。
您可以在groups数组中找到匹配颜色的索引,并输出匹配的组,然后输出$filter
来过滤所有与“ groupKey”匹配的成员。
请注意,当您始终找到匹配的颜色,否则$indexOfArray
返回-1并且您将不会获得预期的结果时,此解决方案将起作用。 为此,您可以添加$cond
运算符以在获取组文档之前检查索引。
db.col.aggregate([
{"$addFields":{
"members":{
"$let":{
"vars":{
"group":{
"$arrayElemAt":["$groups",{"$indexOfArray":["$groups.color","Red"]}]
}
},
"in":{
"$filter":{"input":"$members","cond":{"$eq":["$$this.groupKey","$$group.key"]}}
}
}
}
}}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.