mongodb - How do I use Spring Mongo to group two fields and get a array of one fields based on the other? -


let me give example here:

two entries in collection author:

{ "name" : "joe" "book" : "a" }, { "name" : "joe" "book" : "b" } 

now, if use aggregation function in mongo via spring mongo, grab books name joe, coded like:

aggregation agg = newaggregation(map.class, group("name", "book"));  aggregationresults<map> results = mongotemplate.aggregate(agg, "author",                 map.class); 

obviously 2 maps way, 1 has entry {"name":"joe", "book": a}, other has {"name" : "joe", "book" : "b"}

but if want 1 result back, 1 entry :

{"name" : joe, "books" : ["a", "b"]}? 

i'm not sure if reachable using 1 query. achieved multiple steps, i'd hate do..

you need use $addtoset operator in $group pipeline. return array of unique values ["a", "b"] results applying $group expression each document in group of documents share same group key "name". in mongo shell have

db.author.aggregate([     {         "$group": {             "_id": "$name",             "books": {                 "$addtoset": "$book"             }         }     } ]); 

which brings desired result

{     "result" : [          {             "_id" : "joe",             "books" : [ "b", "a" ]         }     ],     "ok" : 1 } 

the equivalent spring aggregation:

aggregation agg = newaggregation(map.class, group("name").addtoset("book").as("books"));  aggregationresults<map> results = mongotemplate.aggregate(agg, "author", map.class);