tarunkumar
tarunkumar

Reputation: 891

Mongodb java springdata unable to get result for date equals query

I have inserted some test records to the mongo database with following structure.

{ "_id" : ObjectId("5563fe96a826638b48c77c26"),

"date" : ISODate("2015-05-02T07:00:00.326Z"),

"createdDate" : ISODate("2015-05-26T05:03:18.899Z"),

"updatedDate" : ISODate("2015-05-26T05:03:18.899Z"),

"status" : 0

}

Now when I try to query it using Spring data or via MongoDB I am always getting returned result list size to be 0.

Calendar  calendar = Calendar.getInstance();
calendar.set(2015, 4, 2, 0, 0, 0);
Query query = new Query();      
query.addCriteria(Criteria.where("date").is(calendar.getTime());
List<DateRecord> attendanceList = findAll(query, DateRecord.class);
System.out.println(attendanceList.size());

I am getting a very similar result for BasicDBObject, list of size 0.

DBCursor cursor;
BasicDBObject query1 = new BasicDBObject();
query1.append("date", calendar.getTime());

cursor = collection.find(query1);
System.out.println("Total objects returned "+cursor.size());    

Any pointers on same will be highly appreciated. All I just want that data should be returned based upon year,month and day and any timestamp field values should be ignored.

Upvotes: 0

Views: 909

Answers (1)

Pelit Mamani
Pelit Mamani

Reputation: 2381

I suggest using a different query - look for date greater than 2015-4-2 00:00:00 and explicitly less than 2015-4-3:00:00:00

Another approach, that I'm less enthusiastic about, would be to to add a field to the document just for the search purpose (e.g. "dateWithoutHour" calculated by java just before saving a document, and assuming data doesn't arrive from other sources). I don't like it, because I prefer my data to be pure logic and not change any time someone comes up with a new search requirement... but sometimes I had to resort to it).

And as always, when facing a difficult query it's tempting to consider $where , but I won't recommend it because it can't use indices.

Upvotes: 0

Related Questions