0

I need guidance in translating the following MongoDB query in to a Java program that uses a Java DB driver to retrieve data. Any guidance would be really appreciated.

db.playerscorecollection.aggregate([ 

{ 

 $unwind: "$scorearray"

}, 

{ 
$group: 
{ 

   _id: {player:'$player,venue:'$venue'}, maxScore: { $max: "$scorearray.score" } 

} 

} 

]); 
2
  • Actually I got it wrong, the mongodb query that I posted in the question is grouping the results based on player and venue and then caluclating the max score , I need to get the venue for the max score only , if I take venue out of the id field I get an error , can someone help? Commented Jul 13, 2013 at 4:43
  • You need to learn to say what error you get! In any case, you can change the _id part to: _id : '$venue' — but of course it doesn't return players then. Commented Jul 13, 2013 at 15:26

1 Answer 1

1

The documentation and tutorial at http://docs.mongodb.org/ecosystem/tutorial/use-aggregation-framework-with-java-driver/ is quite extensive. Please read that first before reading the remainder of this answer. In general, something like this should work:

// create our pipeline operations, first the $unwind
DBObject unwind = new BasicDBObject( "$unwind", "$scorearray" );

DBObject groupIdFields = new BasicDBObject( "player", "$player" );
groupIdFields.put( "venue", "$venue" );
DBObject groupFields = new BasicDBObject( "_id", groupIdFields );
groupFields.put( "maxScore", new BasicDBObject( "$max", "$scorearray.score" ) );
DBObject group = new BasicDBObject( "$group", groupFields );

// run aggregation
AggregationOutput output = MDB.getCollection("playerscorecollection").aggregate( unwind, group );
Sign up to request clarification or add additional context in comments.

5 Comments

Thank You ! That was accurate.
Thank You , how can I add distinct to it. ?
Actually I got it wrong, the mongodb query that I posted in the question is grouping the results based on player and venue and then caluclating the max score , I need to get the venue for the max score only , if I take venue out of the id field I get an error , can someone help?
You need to learn to say what error you get! In any case, you can change the _id part to: _id : '$venue' — but of course it doesn't return players then
Anybody know what happened to the page t docs.mongodb.org/ecosystem/tutorial/… It's not there anymore. Is there an update somewhere with the new API in version 3?

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.