MongoDB group by aggregation query



我的数据是:

[
{ type: 'software' },
{ type: 'hardware' },
{ type: 'software' },
{ type: 'network' },
{ type: 'test' },
...
]

我想通过聚合管道创建一个MongoDB组来返回这样的数据:结果中我只想要3个对象结果{_id: 'other', count: 2}中的第三个对象,这应该是除软件和硬件以外的其他类型的计数之和

[
{_id: 'software', count: 2},
{_id: 'hardware', count: 1},
{_id: 'other', count: 2},
]

如果这些数据是单独的文档,这就是您需要的确切查询(MongoPlayground)。只需在组前加上$project级,再加上$switch算子。(如果这些字段数据是数字,你可能要检查$bucket

db.collection.aggregate([
{
"$project": {
type: {
"$switch": {
"branches": [
{
"case": {
"$eq": [
"$type",
"software"
]
},
"then": "software"
},
{
"case": {
"$eq": [
"$type",
"hardware"
]
},
"then": "hardware"
}
],
default: "other"
}
}
}
},
{
"$group": {
"_id": "$type",
"count": {
"$sum": 1
}
}
}
])

另外,我想建议避免使用字段名type。实际上它并不保留在MongoDB中,但是它可能会带来冲突与一些驱动程序,因为在模式/模型文件中,类型字段被引用到字段的确切BSON类型。

最新更新