Query de MongoDB agregando por mês e ano

De Basef
Revisão de 19h21min de 21 de agosto de 2016 por Admin (discussão | contribs)

(dif) ← Edição anterior | Revisão atual (dif) | Versão posterior → (dif)
Ir para: navegação, pesquisa

Segue abaixo como agregar a collection "collection" por mês e ano (pelo campo "createdAt").

Query do Mongo:

db.collection.aggregate(
    {$project : {
         year : {$year : "$createdAt"}, 
         month : {$month : "$createdAt"}
    }},
    {$group : {
         _id : {year : "$year", month : "$month"}, 
         count : {$sum : 1}
    }}
)

A query acima pode ser executada diretamente no MongoDB.

No Java, com query string:

List criteria = (List) JSON.parse(
    "[" +
        "{ " +
            "$project: { " +
                "year: {$year: \"$createdAt\"}, " +
                "month: {$month: \"$createdAt\"} " +
            "} " +
        "}, " +
        "{ " +
            "$group: { " +
                "_id: { " +
                    "year: \"$year\", " +
                    "month: \"$month\"" +
                "} " +
            "} " +
        "} " +
    "]"
);
 
MongoTemplate mongo = new MongoTemplate(new Mongo("localhost"), "myMongoDb");
 
AggregationOutput output =
    mongo.getCollection("collection").aggregate(criteria);

Repare que foi usado a mesma query do primeiro exemplo.

No Java, utilizando objetos:

List criteria = asList(
    new BasicDBObject("$project",
        new BasicDBObject("year", new BasicDBObject("$year", "$createdAt"))
        .append("month", new BasicDBObject("$month", "$createdAt"))
    ),
    new BasicDBObject("$group",
        new BasicDBObject("_id",
            new BasicDBObject("year", "$year")
            .append("month", "$month")
        )
        .append("count", new BasicDBObject("$sum", 1))
    )
);
 
MongoTemplate mongo = new MongoTemplate(new Mongo("localhost"), "myMongoDb");
 
AggregationOutput output =
    mongo.getCollection("collection").aggregate(criteria);

Repare que continuamos usando a mesma query do primeiro exemplo, porém, foi construída utilizando objetos.