Java/MongoDB query by date

后端 未结 6 1394
南旧
南旧 2020-12-01 10:04

I stored a value as a java.util.Date() in my collection, but when I query to get values between two specific dates, I end up getting values outside of the range. Here\'s my

相关标签:
6条回答
  • 2020-12-01 10:44

    Search Date with specific format following steps are that this also work in mongo 3.0

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("yyyy.MM.dd");
    

    First convert your date in your specific format, you can use any format and parse your date with above format and then pass in query.

    String date ="2014.01.02"; 
    String data1 ="2014.01.10";
    Date startDate = simpleDateFormat.parse(date);  
    Date endDate = simpleDateFormat.parse(date1);
    
    BasicDBObject query = new BasicDBObject("fieldName",
       new BasicDBObject("$gte",startDate).append("$lt",endDate ));
    

    So base on your requirement you can search date by giving argument in BasicDBobject.

    0 讨论(0)
  • 2020-12-01 10:46

    What you're doing is querying only with {$lte: toDate} losing $gte operator in the key overwrite. What you want is:

    query.put("dateAdded", BasicDBObjectBuilder.start("$gte", fromDate).add("$lte", toDate).get());
    
    0 讨论(0)
  • 2020-12-01 10:47

    I approach the query like this

    new Document("datetime",Document.parse(
        "{$gte: ISODate('" + new SimpleDateFormat("yyyy-MM-dd").format(fromDate) + "'), 
         $lte: ISODate('" + new SimpleDateFormat("yyyy-MM-dd").format(endDate) + "')}"
    ))
    
    0 讨论(0)
  • 2020-12-01 11:04

    You can do

        import org.bson.conversions.Bson;
        import static com.mongodb.client.model.Filters.*;
        import java.text.SimpleDateFormat;
    
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
        Bson filter = Filters.and(gte("date_field", format.parse("2018-10-01")),
                                lt("date_field", format.parse("2019-10-01")))
    
    0 讨论(0)
  • 2020-12-01 11:06

    If you are using MongoTemplate of Spring-Data Mongodb, you can do the same in following way:-

    public List<Link> getLinksBetweenDate(Date startDate, Date endDate) {
                Query query = new Query().addCriteria(Criteria.where("updatedOn").gt(startDate).lte(endDate));
                return mongoTemplate.find(query, Link.class);
            }
    
    0 讨论(0)
  • 2020-12-01 11:07

    Using mongo client 3.0

    DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
    Bson filter = new Document("$gte", format.parse("2015-05-01T00:00:00Z")).append("$lt", format.parse("2015-05-02T00:00:00Z"));
    long count = db.getCollection("colection").count(new Document("field",filter) );
    
    0 讨论(0)
提交回复
热议问题