2015-04-17 82 views
2

我正在使用Java与MongoDB的Web服务,因为我试图检查日期时间是否说“2015-04-16 16 :32:49" 位于日期时间存在于字段START_TIME和END_TIME从table.In MySQL之间的我尝试以下查询要检查一个日期是否在MongoDB的列中的两个日期之间使用JAVA

SELECT * FROM表名其中EMPLOYEE_ID = 101和“2015年4月16日 16 :start_time和end_time之间的32:49';

我试图通过使用下面的代码

BasicDBObject whereQuery = new BasicDBObject(); 
      whereQuery.put("employeeID", "101"); 
      String date = "2015-04-17 11:02:49"; 
      whereQuery.put(date, new BasicDBObject("$gt", "start_time ") 
        .append("$lt", "end_time ")); 
DBCursor cursor = col.find(whereQuery); 

复制使用Java MongoDB中相同,但代码是不工作的,它不是比较表两列中指定的日期,是什么是正确的语法做

,如果我尝试此代码

whereQuery.put(someOtherField, new BasicDBObject("$gt", "2015-04-17 11:02:49") 
         .append("$lt", "2015-04-19 11:02:49")); 

这是工作,我需要的语法比较两个字段的日期字符串在整个表

+0

“start_time”和“end_time”的数据类型是什么? – thegreenogre

+0

'String date'用于和MongoDB的'date'类型字段进行比较。当你传递'java.sql.Date'时会发生什么? – Sridhar

+0

MongoDB中的DATE数据类型 – Vicky

回答

1

您所查询的大致翻译为:

select * from tablename where Employee_id =101 and '2015-04-16 16:32:49' > "start_time" and '2015-04-16 16:32:49' < "end_time"; 

你比较字符串"start_time""end_time"'2015-04-16 16:32:49'

正确的查询将是: -

BasicDBObject whereQuery = new BasicDBObject(); 
     whereQuery.put("employeeID", "101"); 
     String date_string = "2015-04-17 11:02:49"; 
     DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); 
     Date date = format.parse(date_string); 
     whereQuery.put("start_time", new BasicDBObject("$lt", date)); 
     whereQuery.put("end_time", new BasicDBObject("$gt", date)); 
DBCursor cursor = col.find(whereQuery); 

您可以使用普通的Java日期对象。

+0

谢谢我认为它应该可以工作,这是记录必须提取但它是没有得到这个{_id“:ObjectId(”552fba6577c7ec1f6c2ec830“), ”blockID“:”B“, “floorID”:“3”, “employeeName”:“xxx”, “employeeID”:“13”, “roomRange”:“1,2,3”, “isActive”:0, “updateDateTime” :ISODate(“2015-04-16T13:34:28.781Z”), “shiftStartTime”:ISODate(“2015-04-16T11:02:49.000Z”), “shiftEndTime”:ISODate(“2015-04- 18T11:02:49.000Z“) } – Vicky

+0

如果您正在查找完全匹配,您应该使用'$ gte'和'$ lte'来代替'$ gt'和'$ lt'。 – thegreenogre

+0

这是正在运行但未获取记录的mongo查询{“employeeID”:“13”,“isActive”:0,“shiftStartTime”:{“$ gt”:{“$ date”:“2015-01- “移动时间”:{“$ lt”:{“$ date”:“2015-01-17T05:32:49.000Z”}}} – Vicky

相关问题