0

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

1 Answer 1

0

Your query seems fine. Try this as well:

MatchOperation matchOperation = Aggregation.match(
          new Criteria("zip").is(zipCode).and("city").is(cityName));
GroupOperation groupOperation = Aggregation.group("userId", "user");
ProjectionOperation projectionOperation = Aggregation.project().andExpression("_id.userId").as("userId").andExpression("_id.user").as("user");
Aggregation  aggregation = Aggregation.newAggregation(matchOperation, groupOperation, projectionOperation);
AggregationResults<UserDTO> result = mongoTemplate.aggregate(aggregation, UserDetails.class, UserDTO.class);

Also check, what is the value of result.getUniqueMappedResult() or result.getMappedResults().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.