Thursday, May 3, 2018

Count how much unique field values in mongo

db.getCollection('myCollection').aggregate( 
    {$group: {"_id":"$username"}},
    {$group: {"_id":1, count:{$sum:1}}
})

db.getCollection('myCollection').aggregate( [
    {$match: { "_id.appId":"23893259736", "status" : 1 } },
    {$group: {"_id":"$_id.deviceId"}},
    {$group: {"_id":1, count:{$sum:1}}}

])


Criteria criteria = SearchQueryBuilder.parse(query);
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.match(criteria),
Aggregation.group("username"),
Aggregation.group("username").count().as("count")
);
try {
AggregationResults aggregationResults = mongoTemplate.aggregate(aggregation, Devices.class, GroupAndCount.class);
GroupAndCount cbg = aggregationResults.getMappedResults().iterator().next();
return cbg.count;
} catch (Exception e) {
return 0;
}

private static final class GroupAndCount {
@Id
private Integer _id;
private Integer count;
}

No comments: