MongoDB
 sql >> Datenbank >  >> NoSQL >> MongoDB

Spring Data Mongo - Perform Distinct, möchte aber keine eingebetteten Dokumente in die Ergebnisse ziehen

Die Aggregation erhält die eindeutige departments.deptCd Werte (plus andere 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 }
}
] )

Die Ausgabe:

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

[ BEARBEITEN HINZUFÜGEN ]

Code mit 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);