Reputation: 158
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
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();
Upvotes: 1
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