简体   繁体   中英

Unable to find a document in Mongodb where exact date match in java

Statement: I am trying to get the documents from MongoDB collection (Emp) using java.

Condition: Where it matches with the DOB(Date of birth) of a person.

Problem: However, it never returns a record.

But it works perfectly for other fields such as EmpID or EmpName etc. The document of my collection looks like this,

{ 
    "_id" : ObjectId("5d4d9059f0b31921a4916a0c"), 
    "EmpID" : "1001", 
    "EmpName" : "John", 
    "Sal" : 30000.0, 
    "DOB" : ISODate("1989-06-09T18:30:00.000+0000"), 
    "Age" : 31.0
}

Please find the following java code that I have tried,

BasicDBObject dbo = new BasicDBObject();
dbo.append("DOB", new BasicDBObject("$eq","1989-06-10T00:00:00.000"));

FindIterable<Document> doc = coll.find(dbo);

for (Document dox : doc) 
{   
    System.out.println(dox.toJson());
}

Please help

For ISODate it's needed to pass the Date object in BasicDBObject , not String , also timezone must be provided:

dbo.append("DOB", new BasicDBObject("$eq",new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXX").parse("1989-06-10T00:00:00.000+0000")));

For Date Of Birth better to use $gte and $lt comparition operators together in order to take full range of single day, like that:

Date dayStart = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXX").parse("1989-06-10T00:00:00.000+0000");
Date dayEnd = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXX").parse("1989-06-11T00:00:00.000+0000");

BasicDBObject query = new BasicDBObject("Date", new BasicDBObject("$gt", dayStart).append("$lte", dayEnd));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM