Query using date range in MongoDB in Java
I am new to using MongoDB. I fill it with receipts, for example: one acknowledgment looks like this:
{
"_id" : {
"$oid" : "510fa057c6f818c2bfd0b279"
} ,
"StoreName" : "Metro" ,
"StoreNumber" : 521 ,
"Items" : [ {
"ItemName" : "Battery" ,
"ItemManufacturer" : "Duracell" ,
"ItemPrice" : 12 ,
"ItemQuantity" : 2 ,
"ItemTotalPrice" : 24
} ,
{
"ItemName" : "TV CRT 25 inch" ,
"ItemManufacturer" : "Toshiba" ,
"ItemPrice" : 1659 ,
"ItemQuantity" : 1 ,
"ItemTotalPrice" : 1659
} ,
{
"ItemName" : "Mobile" ,
"ItemManufacturer" : "Nokia" ,
"ItemPrice" : 2966 ,
"ItemQuantity" : 4 ,
"ItemTotalPrice" : 11864
}
] ,
"Date" : {
"$date" : "2012-06-16T01:21:11.758Z"
} ,
"Total" : 13547
}
I need to make a query where I specify a date range to get all receipts in that range. I tried the following query but it returns nothing.
BasicDBObject query =
new BasicDBObject(
"Date",
new BasicDBObject(
"$gt",
"2012-06-20T10:05:21.968Z"
).append(
"$lte",
"2012-09-24T05:29:43.031Z"
)
);
+3
source to share
2 answers
MongoDB dates work in conjunction with java.util.Date. Change your query to something like this:
Date start = new java.util.Date(2012, 06, 20, 10, 05);
Date end = new java.util.Date(2012, 06, 20, 10, 30);
BasicDBObject query = new BasicDBObject("Date",
new BasicDBObject("$gt", start)).
append("$lte", end) ));
+7
source to share
You may try:
Date gtDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").parse("2012-06-20T10:05:21.968");
Date lteDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").parse("2012-09-24T05:29:43.031");
BasicDBObject dateQueryObj = new BasicDBObject("Date", new BasicDBObject("$gt", gtDate).append("$lte", lteDate));
DBCursor cursor = collection.find(dateQueryObj);
0
source to share