Marco de agregación MongoDB en 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.

p.ej

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.

preguntado el 31 de julio de 12 a las 10:07

3 Respuestas

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);

contestado el 15 de mayo de 14 a las 20:05

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

Tu puedes hacer simple aggregation usar contar(), distinto() y grupo() comandos a través de DBCollection class of the MongoDB Java driver.

For more advanced queries in the current production version of MongoDB (2.0.6) you can use Mapa reducido mediante el MapReduceCommand class.

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

Respondido 01 ago 12, 13:08

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 - Benoît Guérout

@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. - Stennie

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.

Preguntas relacionadas:

contestado el 23 de mayo de 17 a las 13:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.