Java Driver & MongoDB Aggregation Example

The following snippet is an example of how to query document in Mongo database, using Group By, Count, Limit, Sort, and Match.

This will count top 20 referrers descendingly-sorted, excluding any document with empty value (“”) in _id field.

If you’re not familiar with Aggregation concept, the following article about Aggregation Pipeline might helps.

// get from "Accounts" collection
DBCollection accountsColl = db.getCollection("Accounts");

// create new BasicDBObject that will be used to
// count based on $referrer field
DBObject groupFields = new BasicDBObject( "_id", "$referrer");
// return result as "count" field that based on the sum
// of similar value in $referrer field. Everytime a similar value
// is found, the count is given a $sum operation by 1.
groupFields.put("count", new BasicDBObject( "$sum", 1));
DBObject group = new BasicDBObject("$group", groupFields );

// create new BasicDBObject  that will ne used to filters out
// an empty string in $referrer field
DBObject matchFields = new BasicDBObject();
matchFields.put("_id", new BasicDBObject("$ne",""));
DBObject match = new BasicDBObject("$match", matchFields);

// create new BasicDBObject that limit query result in only 20 rows
DBObject limit = new BasicDBObject("$limit", 20);

// create new BasicDBObject that sort the result
// based on count, descendingly
DBObject sortFields = new BasicDBObject("count", -1);
DBObject sort = new BasicDBObject("$sort", sortFields );

// aggregate all conditions above
AggregationOutput output = accountsColl.aggregate(group, match,
sort, limit);
return output.getCommandResult().toString();