mongoTemplate嵌套字段的聚合统计

简单说明

个人理解:
基于嵌套字段的统计,是要先将外层“unwind”,类似于Vue的解构。
后面使用的时候还需要在该属性前加"$"。

但是查询并不需要如此,直接通过"."即可。

Aggregation.match(Criteria.where("size.h").gte(9.0)),注释掉之后,统计结果就没有了uom为"in"的
代码如下:

 @Test
    void testnewAggri(){
        // 数据来自:https://jinmu.whaleal.com/MongoDB-Manual-zh/docs/04-crud/02-query-documents/01-query-embedded-documents.html
        // db.tt.insertMany( [
        //    { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
        //    { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },
        //    { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
        //    { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
        //    { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }
        //]);
        Aggregation aggregation5 =
                Aggregation.newAggregation(
                        Aggregation.match(Criteria.where("size.h").gte(9.0)),
                        Aggregation.unwind("size"),
                        Aggregation.group("$size.uom").avg("$size.w").as("平均分").min("$size.w").as
                                ("最小值").max("$size.w").as("最大值").sum("$size.w").as("求和"));
        AggregationResults<BasicDBObject> outputTypeCount5 =
                template.aggregate(aggregation5, "tt", BasicDBObject.class);

        for (Iterator<BasicDBObject> iterator = outputTypeCount5.iterator(); iterator.hasNext(); ) {
            DBObject obj = iterator.next();
            System.out.println(obj);
        }
    }

代码运行结果如下:

{"_id": "cm", "平均分": 22.083333333333332, "最小值": 15.25, "最大值": 30.0, "求和": 66.25}

如果注释掉:Aggregation.match(Criteria.where("size.h").gte(9.0)),,运行结果如下:

{"_id": "in", "平均分": 11.0, "最小值": 11.0, "最大值": 11.0, "求和": 22.0}
{"_id": "cm", "平均分": 22.083333333333332, "最小值": 15.25, "最大值": 30.0, "求和": 66.25}
欢迎大家留言,以便于后面的人更快解决问题!另外亦欢迎大家可以关注我的微信公众号,方便利用零碎时间互相交流。共勉!

posted @ 2023-02-07 09:30  东方欲晓_莫道君行早  阅读(306)  评论(0编辑  收藏  举报