如何在mongoDB中对同一个查询使用group by和lookup?
我有一个mongo db集合filter_weights:
` {
"category": "laptops",
"counter": 7,
"filter_id": "brands"
}
我有第二个集合filter_options_weights:
{
"category": "laptops",
"counter": 2,
"filter_id": "brands",
"filter_option_value": "Dell"
},
` {
"category": "laptops",
"counter": 5,
"filter_id": "brands",
"filter_option_value": "Apple"
}
我想得到的outpout是:
{
"category": "laptops",
"counter": 7,
"filter_id": "brands"
"filter_option_value": [{"Dell": 2}, {"Apple": 5}]
},
我试着这样做
`db.filter_weights.aggregate(
{$match: {$and: [{category: "smartfony"}]}},
{$group: { _id : "$filter_id", totalSum :{$sum: "$counter"} }},
{
$lookup:
{
from: "filter_values_weights",
localField:"filter_id",
foreignField: "filter_id",
as :"filter_id"
}
})`
但是我不明白如何在同一个查询中使用lookup和group by
1条答案
按热度按时间sc4hvdpw1#
$match
阶段$group
-按filter_id
分组。此阶段之后的输出将不再有filter_id
字段,您应该参考_id
。而要获得category
,您可以考虑使用$first
运算符。$lookup
-使用_id
作为localField。连接集合应该是 filter_options_weights,而不是 filter_values_weights。并以filter_option_value
的形式返回联接的集合结果。$set
-通过$map
将filter_option_value
字段转换为新数组来设置filter_option_value
字段,并使用key设置每个文档:filter_option_value
和值:counter
。Demo @ Mongo Playground