Yii2 MongoDB明显不计

How to get count distinct values from the collection using query? Now I am using this solution:

$collection = Yii::$app->mongodb->getCollection('collection_name');
$result = $collection->distinct('field_id');
return count($result);

Collection example:

    {
       {a: 2},
       {a: 2},
       {b: 3},
       {c: 4}    
    }

Result must be:

3

You can use the aggregation framework for this:

$collection = Yii::$app->mongodb->getCollection('collection_name');
$result = $collection->aggregate(
    array('$group' => array(
        '_id' => '$field_id'
    )),
    array('$group' => array(
        '_id' => 1,
        'count' => array( '$sum' => 1 )
    ))
);

Try this not tested but you can get your results, make some changes if exception occur.

use yii\mongodb\Query;
$query = new Query;
$count = $query->from('collection_name')->distinct('field_id')->count();

More detail