Query using range of date in MongoDB in Java

后端 未结 2 1702
野趣味
野趣味 2021-01-06 17:24

I am new at using MongoDB. I have it filled with receipts, for example: one receipt looks like this :

{ 
  \"_id\" : { 
          \"$oid\" : \"510fa057c6f818         


        
相关标签:
2条回答
  • 2021-01-06 17:56

    You could 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 讨论(0)
  • 2021-01-06 18:09

    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) ));
    
    0 讨论(0)
提交回复
热议问题