Andrii Lytvynenko
Andrii Lytvynenko

Reputation: 158

Yii2 MongoDB distinct count

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

Upvotes: 1

Views: 2178

Answers (2)

Muhammad Shahzad
Muhammad Shahzad

Reputation: 9652

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

Upvotes: 1

chridam
chridam

Reputation: 103375

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 )
    ))
);

Upvotes: 4

Related Questions