我尝试按聚合中的两个不同字段进行分组,以避免重复。我有以下案例:
'$project' => [
'type1' => '$field1',
'type2' => '$field2',
'category1' => [
'$cond' => [
['$gt' => ['field3', ' ']],
1,
0
]
],
'category2' => [
'$cond' => [
['$eq' => ['$field4', 1]],
1,
0
]
],
],
],
['$group' => [
'_id' => '$type1',
'total' => ['$sum' => 1],
'category1' => ['$sum' => '$category1'],
'category' => ['$sum' => '$category2']
]
],
['$sort' => ['_id.$type1' => 1, '_id.type1' => 1]]
在上面的示例中,我使用$ field1对它们进行分组。是否可以在同一个聚合中按$ field 2对相同的数据进行分组?
答案 0 :(得分:0)
是的,它可能。 如果要对两个字段进行分组,则查询非常简单:
db.collection.aggregate([
{$group:{_id:{field1:"$field1", field2:"$field2"}..other accumulators here..}}
])