Mudanças entre as edições de "Query de MongoDB agregando por mês e ano"

De Basef
Ir para: navegação, pesquisa
(Criou página com 'Query do Mongo: <source lang="javascript"> db.collection.aggregate( {$project : { year : {$year : "$createdAt"}, month : {$month : "$createdAt"} }}...')
 
Linha 21: Linha 21:
 
         "{ " +
 
         "{ " +
 
             "$project: { " +
 
             "$project: { " +
                 "year: {$year: \"$date\"}, " +
+
                 "year: {$year: \"$createdAt\"}, " +
                 "month: {$month: \"$date\"} " +
+
                 "month: {$month: \"$createdAt\"} " +
 
             "} " +
 
             "} " +
 
         "}, " +
 
         "}, " +
Linha 47: Linha 47:
 
List criteria = asList(
 
List criteria = asList(
 
     new BasicDBObject("$project",
 
     new BasicDBObject("$project",
         new BasicDBObject("year", new BasicDBObject("$year", "$date"))
+
         new BasicDBObject("year", new BasicDBObject("$year", "$createdAt"))
         .append("month", new BasicDBObject("$month", "$date"))
+
         .append("month", new BasicDBObject("$month", "$createdAt"))
 
     ),
 
     ),
 
     new BasicDBObject("$group",
 
     new BasicDBObject("$group",

Edição das 19h18min de 21 de agosto de 2016

Query do Mongo:

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

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(Transaction.collection).aggregate(criteria);

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(Transaction.collection).aggregate(criteria);