Query de MongoDB agregando por mês e ano
De Basef
Revisão de 20h18min de 21 de agosto de 2016 por Admin (discussão | contribs) (Criou página com 'Query do Mongo: <source lang="javascript"> db.collection.aggregate( {$project : { year : {$year : "$createdAt"}, month : {$month : "$createdAt"} }}...')
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: \"$date\"}, " + "month: {$month: \"$date\"} " + "} " + "}, " + "{ " + "$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", "$date")) .append("month", new BasicDBObject("$month", "$date")) ), 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);