I am new to Mongo db and aggregation query. I want to perform distinct on 2 fields i.e. userId and user in mongo db collection with name "userDetails". I am able to execute below query and get the distinct documents from Mongo db using Robo 3T. But, I am trying to execute the same query using spring data MongoTemplate but getting empty result object in java. Need help to translate the below query in Java using Mongo template.
db.userDetails.aggregate([
{"$match" : {zip:"52034", city:"Delhi"}},
// group by userId, userName to get distinct document
{"$group" : {_id : {userId:"$userId", user:"$user"}}},
// Clean up the output
{"$project" : {_id:0, userId:"$_id.userId", user:"$_id.user"}}
])
Below is the java code for above query using Spring data MongoTemplate, but the result object is empty during execution. UserDetails model class represent the Mongo document and UserDTO is the final response that need to be returned.
MatchOperation matchOperation = Aggregation.match(
new Criteria("zip").is(zipCode).and("city").is(cityName));
GroupOperation groupOperation = new GroupOperation(Fields.fields("userId", "user"));
ProjectionOperation projectionOperation = Aggregation.project().andExclude("_id").and("userId").nested(
Fields.fields("_id.userId"))
.and("user").nested(Fields.fields("_id.user"));
Aggregation aggregation = Aggregation.newAggregation(matchOperation, groupOperation, projectionOperation);
AggregationResults<UserDTO> result = mongoTemplate.aggregate(aggregation, UserDetails.class, UserDTO.class);
Spring data mongodb - 3.0.7 Driver 4.0.4