Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb + Java Drivers. Search by date range

Tags:

java

date

mongodb

This is my first shot at using Mongodb with the java drivers. I can query the database via command line using javascript and the Date() object, however, I am having trouble using the driver. Based on my query, can anybody see what the problem is? Thanks

            Date current = new Date();
            DBCollection coll = db.getCollection("messages");

            BasicDBObject query = new BasicDBObject("created_on", new BasicDBObject("$gte", new Date(current.getYear(), current.getMonth(), current.getDate())).
                    append("created_on", new BasicDBObject("$lt", new Date(current.getYear(), current.getMonth() - 1, current.getDate()))));

            System.out.println("Query: " + query);


            DBCursor cursor = coll.find(query);

Query: { "created_on" : { "$gte" : { "$date" : "2012-12-06T05:00:00.000Z"} , "created_on" : { "$lt" : { "$date" : "2012-11-06T05:00:00.000Z"}}}}

P.S. In case it is not obvious, I'm trying to find all of the records within the last month.

like image 932
tier1 Avatar asked Dec 06 '12 21:12

tier1


1 Answers

Seems like you are constructing the query wrong. Please try the below one:

BasicDBObject query = new BasicDBObject("created_on", //
                      new BasicDBObject("$gte", new DateTime().toDate()).append("$lt", new DateTime().toDate()));

Datetime object is a library which simplies date manipulation in java. You can check that out. http://joda-time.sourceforge.net/

Also morphia is a nice java object-document-mapper (ODM) framework for working with mongodb through java driver. It simplifies querying through java.

https://github.com/jmkgreen/morphia

like image 99
cubbuk Avatar answered Oct 05 '22 18:10

cubbuk