需求:对表数据进行分组后,根据某个字段去重,然后在count
命令行有 db.collection.distinct("someField")
问:用morphia应该怎么写?或者通过原生的mongodb驱动应该怎么做?
如果用聚合的话,怎么才能当查询的结果为null时统计的数量为0,比如sql中的 isNull(count(1), 0)
阿神2017-04-17 15:17:00
BasicDBObject group1 = new BasicDBObject();
BasicDBObject _id = new BasicDBObject();
_id.put("field1", "$field1");
_id.put("field2", "$field2");
group1.put("_id", _id);
BasicDBObject group2 = new BasicDBObject();
group2.put("_id", "$_id.field1");
group2.put("statCnt", new BasicDBObject("$sum", 1));
List<DBObject> aggParam = new ArrayList<>();
aggParam.add(new BasicDBObject("$match", match));
aggParam.add(new BasicDBObject("$group", group1));
aggParam.add(new BasicDBObject("$group", group2));
aggParam.add(new BasicDBObject("$sort", sort));
aggParam.add(new BasicDBObject("$limit", 10));
AggregationOutput output = collection.aggregate(aggParam);
This is the code I actually used. To put it simply, I used group twice to achieve the purpose of deduplicating a certain field in each group
Reference: http://www.cnblogs.com/lori/p/4597341.html
ringa_lee2017-04-17 15:17:00
Call the com.mongodb.DBCollection#distinct
method, corresponding to the command line db.collection.distinct("someField")
in the question.
This will return all the data, so if you just want to get the count, there is no need to use distinct.
You can use aggregate directly.
db.collection.aggregate(
[{
$group:{
_id:"$someField",
count:{$sum:1}
}
}]
)