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" } 

} 

} 

]); 
user1965449
  • 2,849
  • 6
  • 34
  • 51
  • 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? – user1965449 Jul 13 '13 at 04: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. – Derick Jul 13 '13 at 15:26

1 Answers1

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 );
Derick
  • 35,169
  • 5
  • 76
  • 99
  • Thank You ! That was accurate. – user1965449 Jul 12 '13 at 01:20
  • Thank You , how can I add distinct to it. ? – user1965449 Jul 13 '13 at 00:00
  • 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? – user1965449 Jul 13 '13 at 04:42
  • 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 – Derick Jul 13 '13 at 15:27
  • Anybody know what happened to the page t http://docs.mongodb.org/ecosystem/tutorial/use-aggregation-framework-with-java-driver/ It's not there anymore. Is there an update somewhere with the new API in version 3? – user64141 May 08 '15 at 16:38