Spring Data Mongo - Perform Distinct, but doesn't wants to pull embedded documents in results

前端 未结 1 1347
一整个雨季
一整个雨季 2020-12-18 17:11

I\'m developing Spring Boot and Spring Data Mongo example. In this example, I want to get the distinct departments only, but I dont want to fecth subdepartments

1条回答
  •  醉梦人生
    2020-12-18 17:55

    The aggregation gets the distinct departments.deptCd values (plus other details):

    db.collection.aggregate( [
    {
        $group: { _id: "$departments.deptCd", 
                 deptName: { $first: "$departments.deptName" },
                 status: { $first: "$departments.status" }
        }
    },
    {
        $project: { deptCd: "$_id", _id: 0, deptName: 1, status: 1 }
    }
    ] )
    

    The output:

    { "deptName" : "Tax Handling Dept", "status" : "A", "deptCd" : "Tax" }
    


    [ EDIT ADD ]

    Code using Spring Data MongoDB v2.2.7:

    MongoOperations mongoOps = new MongoTemplate(MongoClients.create(), "testdb");
    Aggregation agg = Aggregation.newAggregation(
        Aggregation.group("departments.deptCd")
            .first("departments.deptName").as("deptName")
            .first("departments.status").as("status"),
        Aggregation.project("deptName", "status")
            .and("_id").as("deptCd")
            .andExclude("_id")
    );
    AggregationResults results = mongoOps.aggregate(agg, "collection", Document.class);
    results.forEach(System.out::println);
    

    0 讨论(0)
提交回复
热议问题