Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

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. What Query do I need to change?

db.employees.distinct("departments");

Data:

{
    "firstName" : "Laxmi",
    "lastName" : "Dekate",
    .....
    .......
    .....

    "departments" : {
        "deptCd" : "Tax",
        "deptName" : "Tax Handling Dept",
        "status" : "A",
        "subdepts" : [ 
            {
                "subdeptCd" : "1D",
                "subdeptName" : "Tax Clearning",
                "desc" : "",
                "status" : "A"
            }
        ]
    },
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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<Document> results = mongoOps.aggregate(agg, "collection", Document.class);
results.forEach(System.out::println);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...