silvestrairwave silvestrairwave - 1 year ago 94
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.

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: { date: new ISODate( "2013-08-05T15:24:15" ) } ); { date: new ISODate( "2013-08-05T15:24:19" ) } ); { date: new ISODate( "2013-08-05T15:24:25" ) } ); { date: new ISODate( "2013-08-05T15:24:32" ) } ); { date: new ISODate( "2013-08-05T15:24:45" ) } ); { date: new ISODate( "2013-08-05T15:25:15" ) } ); { date: new ISODate( "2013-08-05T15:25:15" ) } ); [
{ $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 Source

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", "$");
    projectFields.put("count", 1);
    final DBObject project = new BasicDBObject("$project", projectFields);

    final AggregationOutput aggregate = collection.aggregate(group, project);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download