0

Hi I want to query MONGO using java.

I have a query like below:
db.flights.find({"timestamp" : {"$lte": new Date("2014-09-05T00:00:00.001Z")}}).count()

Which gives output as 68

When I try to get using java code like below:

table = db.getCollection("flights");
DBObject match = new BasicDBObject();
Date endDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").parse("2014-09-05T00:00:00.001Z");     
match.put("timestamp", new BasicDBObject("$lte", endDate));
int count=table.find(match).count();
System.out.println(collections+" "+"COUNT : "+count);  

The output is 48.

Can anybody tell me the issue in code ??

Amaresh
  • 3,231
  • 7
  • 37
  • 60
  • What version of Java are you using? If it's JDK 1.7 or later, can you try using the pattern `yyyy-MM-dd'T'HH:mm:ss.SSSX`? Note the **X** at the end. – Anand Jayabalan Dec 16 '14 at 17:24
  • It's possible your Java code is using a different timezone to the server. I believe [the MongoDB server is in UTC](http://stackoverflow.com/a/14983885/653519), but your Java code is probably in your local timezone. Make sure you Java date is also in [UTC](http://www.timeanddate.com/worldclock/timezone/utc). – Trisha Dec 17 '14 at 11:17

1 Answers1

0
saving format 

DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
DateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
className classObject=null; 
Date d1=new Date();
classObject.setDateColumn(format.parse(format.format(d1)));

/---------------------------------------------------/

checking format 

Date d1=new Date();
Date startDate=format.parse((formatDate.format(d1)+" 00:00:00"));
Date endDate=format.parse((formatDate.format(d1)+" 23:59:59"));
classObject=classNameService.classObjectCount(startDate,endDate);


/---------------------------------------------------/

service method

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;

@Autowired(required=true)
private MongoTemplate mongoTemplate;

                       className classObject=null;         
                        Query query = new Query();

            query.addCriteria(org.springframework.data.mongodb.core.query.Criteria.where("testId").in(testId));
            query.addCriteria(org.springframework.data.mongodb.core.query.Criteria.where("testDate").gte(startDate).lte(endDate));
            List<className> classNames=mongoTemplate.find(query, className.class);//put your class name..className 
            if(classNames.size()>0)
                classObject=classNames.get(0);
Basker Ammu
  • 105
  • 1
  • 7