2

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.

1

3 Answers 3

2
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);
Sign up to request clarification or add additional context in comments.

1 Comment

@cpburnz you are right I was simply trying to put one answer. now I added the java implementation for it
1

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.

2 Comments

Aggregation helper will be available in version 2.9.0 (not 1.9.0). BTW, you can already use new Aggregation Framework with Jongo : jongo.org/#querying
@BenoitGuerout: Thx, off by 1 :-p. Corrected. The 2.9.0 Java driver isn't officially released yet, but it's possible to test with a github checkout of mongodb-java-driver.
0

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:

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.