0

我试图按聚合中的两个不同字段进行分组,以避免重复。我有以下情况:

'$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 对相同的数据进行分组?

4

1 回答 1

0

是的,有可能。如果要对两个字段进行分组,则查询很简单:

db.collection.aggregate([
{$group:{_id:{field1:"$field1", field2:"$field2"}..other accumulators here..}}    

])
于 2018-04-14T21:14:40.473 回答