Blue Sky
Blue Sky

Reputation: 827

java mongodb search on a given date

We have a user_audit entity(table) in mongodb which stores all the login/logout information. For example,

"_id" : ObjectId("5228cf0156961de6693b74c0"),
"active" : true,
"fname" : "Tom",
"lastlogin" : ISODate("2013-09-05T18:35:45.608Z"),
"lastloginip" : "0:0:0:0:0:0:0:1",
"lname" : "Bailey",
"lastlogout" : ISODate("2013-09-05T18:36:45.568Z"),

There are thousands of records in this table in production.

Now, the admin wants to look for all the logins on a particular date. i am not able to look for exact match of date because of the "time" information attached to ISODate in the "lastlogin" field. In Java, new Date() had been used to insert this field value. The issue is the time information keeps changing for logins on a particular day.

Tried,

query.put("lastlogin", new BasicDBObject("$lte", givenDate).append("$gte", givenDate));

Obviously it does not return results because the time part of the date does not match.

The query passed from Java to mongo is:

 query={ "lastlogin" : { "$lte" : { "$date" : "2013-09-05T04:00:00.000Z"} , "$gte" : {     
"$date" : "2013-09-05T04:00:00.000Z"}}}

[Note: It defaults to 04:00:00.000Z always if we format with MM_dd_yyyy in java, not sure why..]

The issue is we have a lot of records in production database. For fresh records, i can blank out the time portion before inserting from Java. But for existing records, not sure how to handle it. How can i get the records on a given date?

Upvotes: 1

Views: 1098

Answers (1)

LFI
LFI

Reputation: 654

According to mongodb cookbook, you are in the right direction. You may just query for something like

query.put("lastlogin", new BasicDBObject("$lt", givenDatePlusOneDay).append("$gte", givenDateAt00h00min));

which is an interval and not the same date.

Upvotes: 0

Related Questions