java - mongodb框架morphia中怎么去重?
高洛峰
高洛峰 2017-04-17 15:15:00
0
2
798

需求:对表数据进行分组后,根据某个字段去重,然后在count

命令行有 db.collection.distinct("someField")

问:用morphia应该怎么写?或者通过原生的mongodb驱动应该怎么做?

如果用聚合的话,怎么才能当查询的结果为null时统计的数量为0,比如sql中的 isNull(count(1), 0)

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
阿神
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

左手右手慢动作

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}
        }
    }]
)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template