记录一些mongodb聚合查询方法

//获取collection
DBCollection colllection = mongoTemplate.getCollection("faceDetectImageDatail");
//按抓拍时间正序排序
DBObject sortFields = new BasicDBObject("snapDate",1);
//均捕获首次出现
List<DBObject> pipeline = Arrays.asList(
        //new BasicDBObject("$match",new BasicDBObject("dataset","d1")),
        new BasicDBObject("$sort", sortFields),
        new BasicDBObject("$group",
                new BasicDBObject("_id","$faceToken")
                        .append("faceToken",new BasicDBObject("$first","$faceToken"))
                        .append("faceImage", new BasicDBObject("$first","$faceImage"))
                        .append("snapDate", new BasicDBObject("$first", "$snapDate"))
        )
);
//output.results为list<map>
AggregationOutput output = colllection.aggregate(pipeline);

//如果有子文档嵌套多条件匹配可以使用
xxx.where("子文档key").elemMatch(Criteria.where("子文档子key").in(xxx))

$facet

?:一次性聚合出count≤3的数量,3<count≤5的数量,5<count≤8的数量,8<count的数量

$facet可以满足需求。注意boundaries是包含低边界,不包含高边界

db.bar.aggregate([{
    $facet: {
        countByCount: [{
            $bucket: {
                groupBy: "$count",
                boundaries: [0, 4, 6, 9],
                default: "Other",
                output: {
                    count: {$sum: 1}
                }
            }
        }]
    }
}])

结果:

{ "countByCount" : [ { "_id" : 0, "count" : 2 }, { "_id" : 4, "count" : 1 }, { "_id" : 6, "count" : 1 }, { "_id" : "Other", "count" : 1 } ] }