toilOverflow
toilOverflow

Reputation: 21

MongoDB aggregation framework in Java

I have a MongoDB collection and I need to find each distinct value in a field, and how many times each value occurs, a bit like the GROUP BY and COUNT functions in SQL.

e.g.

Item name ------ count

Soap ----------- 7
Apples --------- 4
Tin Foil ------- 5

I'm new to MongoDB and haven't really been able to find any documentation that can help me with this. So far, I've been able to return a list of distinct values, but not the count of each one.

I need to do this through the Java MongoDB library.

Upvotes: 2

Views: 8081

Answers (3)

Lealem Admassu
Lealem Admassu

Reputation: 458

db.item.aggregate([
{
    $group: {
        _id: "$name",
        count: {
            "$sum": 1
        }
    }
},
{
    $project: {
        _id: 0,
        name: "$_id",
        count: 1
    }
}
]).pretty();

A java implementation will be like this

    final MongoClient mongoClient = new MongoClient();
    final DB db = mongoClient.getDB("DB_NAME");
    final DBCollection collection = db.getCollection("item");

    final DBObject groupIdFields = new BasicDBObject("_id", "$name");

    groupIdFields.put("count", new BasicDBObject("$sum", 1));
    final DBObject group = new BasicDBObject("$group", groupIdFields);

    final DBObject projectFields = new BasicDBObject("_id", 0);
    projectFields.put("name", "$_id");
    projectFields.put("count", 1);
    final DBObject project = new BasicDBObject("$project", projectFields);

    final AggregationOutput aggregate = collection.aggregate(group, project);

Upvotes: 2

Stennie
Stennie

Reputation: 65363

You can do simple aggregation using count(), distinct(), and group() commands via the DBCollection class of the MongoDB Java driver.

For more advanced queries in the current production version of MongoDB (2.0.6) you can use Map/Reduce via the MapReduceCommand class.

In MongoDB 2.2 (which currently is being tested for release) there is a new Aggregation Framework feature. The 2.9.0 release of the Java driver will include an aggregation helper.

Upvotes: 1

Guido
Guido

Reputation: 47675

I am not a mongodb expert, but it seems a good place to use MongoDB MapReduce capabilies to perform aggregations or to take a look to this link about aggregation in MongoDB.

Related questions:

Upvotes: 0

Related Questions