MongoDB复杂聚合查询与java中MongoTemplate的api对应

MongoDB聚合json脚本

db.getCollection("202303_refund").aggregate([{
    "$match": {
        "courseType": "常规班课",
        "teacherRefundReasonCheck": true,
        "teacherId": {
            "$in": [7544]
        },
        "createTime": "2023-09-08"
    }
}, {
    "$group": {
        "_id": {
            "subject": "$subject",
            "schoolAreaId": "$schoolAreaId",
            "grade": "$grade",
            "classId": "$classId",
            "isRefund": "$isRefund",
            "teacherId": "$teacherId"
        },
        "subject": {
            "$first": "$subject"
        },
        "schoolAreaId": {
            "$first": "$schoolAreaId"
        },
        "grade": {
            "$first": "$grade"
        },
        "classId": {
            "$first": "$classId"
        },
        "isRefund": {
            "$first": "$isRefund"
        },
        "teacherId": {
            "$first": "$teacherId"
        },
        "refundCount": {
            "$sum": 1
        }
    }
}, {
    "$project": {
        "_id": 0,
        "subject": 1,
        "schoolAreaId": 1,
        "grade": 1,
        "classId": 1,
        "refundCount": 1,
        "teacherId": 1,
        "isRefund": {
            "$ifNull": ["$isRefund", 0]
        }
    }
}])

MongoTemplate的API

Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(new Criteria("courseType").is("常规班课")
                        .and("teacherRefundReasonCheck").is(true)
                        .and("teacherId").in(Sets.newHashSet(7544))
                        .and("createTime").is("2023-09-08")
                ),
                Aggregation.group("subject","schoolAreaId","grade","classId","isRefund","teacherId")
                        .first("subject").as("subject")
                        .first("schoolAreaId").as("schoolAreaId")
                        .first("grade").as("grade")
                        .first("classId").as("classId")
                        .first("isRefund").as("isRefund")
                        .first("teacherId").as("teacherId")
                        .count().as("refundCount"),
                Aggregation.project("subject","schoolAreaId","grade","classId",
                        "refundCount","teacherId","isRefund")
        );
        Iterator<RefundResult> iterator = mongoTemplate.aggregate(aggregation, "202303_refund",
                RefundResult.class)
                .iterator();

你可能感兴趣的:(java,mongodb,java,python)