【发布时间】:2021-07-19 18:35:03
【问题描述】:
假设我们有一个包含以下字段的用户集合:
- 年龄:可以是“年轻”或“老”
- company_position:可以是“程序员”、“技术员”或“QA”
- likes_cats: 布尔值
- favourite_sport:可以是“网球”、“足球”或“无”
我想统计有多少老用户 |年轻,喜欢猫,喜欢网球或足球每个公司职位。
我几乎得到了解决方案:
db.testing.aggregate([
{
$group: {
_id: {
age: '$age',
company_position: '$company_position',
likes_cats: '$likes_cats',
favourite_sport: '$favourite_sport',
},
total: { $sum: 1 }
}
},
{
$group: {
_id: '$_id.company_position',
ages: {
$push: {
age: '$_id.age',
total: '$total',
}
},
likes_cats: {
$push: {
age: '$_id.likes_cats',
total: '$total',
}
},
favourite_sport: {
$push: {
age: '$_id.favourite_sport',
total: '$total',
}
},
}
}
])
此解决方案的问题是我将重复值推送到 ages、likes_cats 和 favourite_sport 字段中。如何在结果数组中没有重复值的情况下获得这样的结果?
{
"job" : "technician",
"ages" : [
{
"age" : "old",
"total" : 3
},
{
"age" : "young",
"total" : 4
},
],
"likes_cats" : [
{
"like" : true,
"total" : 3
},
{
"like" : false,
"total" : 1
},
],
"favourite_sport" : [
{
"age" : "tennis",
"total" : 3
},
{
"age" : "football",
"total" : 4
},
{
"age" : "none",
"total" : 4
},
],
},
{ job: 'programmer', ... },
{ job: 'QA', ... },
....
我正在使用 Azure Cosmos DB 的 API for MongoDB,所以只有 mongodb 4.0 api is partially supported
这是游乐场的链接:
【问题讨论】:
标签: mongodb aggregation-framework