silvestrairwave silvestrairwave - 1 month ago 14
Java Question

MongoDB java querying

I have a question, as I have a collection which stores data. Every record has Date in which was added to collection. My question is: I need to get how many items was added per day.I found some query on MongoDB webpage:

db.orders.find( { ord_dt: { $gt: new Date('01/01/2012') } } ).count()

I'm writing everything in Java and have no idea how to do it. Please be lenient, I have started playing with MongoDB week ago. Any help much appreciated.

EDIT:
I have found mongo aggregating thread on stack overflow in which user wants to count records by minute, as I want to count them for example in every day I suppose it should look like this:

db.so.insert( { date: new ISODate( "2013-08-05T15:24:15" ) } );
db.so.insert( { date: new ISODate( "2013-08-05T15:24:19" ) } );
db.so.insert( { date: new ISODate( "2013-08-05T15:24:25" ) } );
db.so.insert( { date: new ISODate( "2013-08-05T15:24:32" ) } );
db.so.insert( { date: new ISODate( "2013-08-05T15:24:45" ) } );
db.so.insert( { date: new ISODate( "2013-08-05T15:25:15" ) } );
db.so.insert( { date: new ISODate( "2013-08-05T15:25:15" ) } );

db.so.aggregate( [
{ $group: {
_id: {
y: { '$year': '$date' },
m: { '$month': '$date' },
d: { '$dayOfMonth': '$date' },
},
count: { $sum : 1 }
} }
] );


However have no idea where to start with java implementation. Any advices please? :(

Answer

don't you need the date fields also to identify how many items are being added on which date?

    final MongoClient mongoClient = new MongoClient();
    final DB db = mongoClient.getDB("DB_NAME");
    final DBCollection collection = db.getCollection("COLLECTION_NAME");

    final Map<String, Object> groupIdMap = new HashMap<String, Object>();
    groupIdMap.put("year", new BasicDBObject("$year", "$date"));
    groupIdMap.put("month", new BasicDBObject("$month", "$date"));
    groupIdMap.put("day", new BasicDBObject("$dayOfMonth", "$date"));

    final DBObject groupIdFields = new BasicDBObject("_id", new BasicDBObject(groupIdMap));

    groupIdFields.put("count", new BasicDBObject("$sum", 1));
    final DBObject group = new BasicDBObject("$group", groupIdFields);

    final DBObject projectFields = new BasicDBObject("_id", 0);
    projectFields.put("year", "$_id.year");
    projectFields.put("month", "$_id.month");
    projectFields.put("day", "$_id.day");
    projectFields.put("count", 1);
    final DBObject project = new BasicDBObject("$project", projectFields);

    final AggregationOutput aggregate = collection.aggregate(group, project);