Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java & MongoDB query for ISODate problems

(I know I just asked another question about this, but the answers lead me to ask this question, I thought it would be appropriate to create another)

I have an object in MongoDB that looks like this:

{
    "id" : NumberLong(12345),
    "dateModified" : ISODate("2015-01-21T19:43:17.440Z")
}

The query I need to create to retrieve this should look like this (the date in the object falls between these two dates):

db.history.find({"dateModified" : { "$gte" : ISODate("2015-01-19T00:00:00.000Z") , "$lte" : ISODate("2015-01-25T00:00:00.000Z")}});

Unfortunately, I'm using Java and things are coming out funny. Here is my Java query:

java.util.Date fromDate;
java.util.Date toDate;
BasicDBObject searchQuery = new BasicDBObject();

searchQuery.put("dateModified", BasicDBObjectBuilder.start("$gte", fromDate).add("$lte", toDate).get());

Pretty much everywhere I go on the internet suggests that I use the above Java code to perform this query, but the text output for this query is:

{"dateModified" : { "$gte" : { "$date" : "2015-01-19T00:00:00.000Z"} , "$lte" : { "$date" : "2015-01-25T00:00:00.000Z"}}

This query returns no results because it isn't querying in the ISODate format. EDIT: What I mean here is that if I use the above query in the mongo shell I get no results, but if I use the first query I posted, I do get results.

My question is why doesn't this automatically convert to ISODate like the everyone says it should? Or, what can I do to make sure this query converts to the ISODate format?

like image 892
the_camino Avatar asked Oct 31 '22 10:10

the_camino


1 Answers

If you actually run that query from Java, it will work. But pasting the text output into the shell will not, because the Java driver's text output format for BSON documents is MongoDB Extended JSON, the same format used by tools such as mongoexport. However, this format is not understood by the shell. There is a Jira issue requesting shell support for extended JSON.

like image 124
jyemin Avatar answered Nov 15 '22 05:11

jyemin