Spring Data MongoDB Date Between

2020-02-17 06:22发布

I use spring data mongodb.

I want the records between two dates. The following MongoDB Query works:

db.posts.find({startDate: {$gte: start, $lt: end}});

My attempted Spring data query object code translation does not work:

Query query = new Query();
query.addCriteria(Criteria.where("startDate").gte(startDate)
                            .and("startDate").lt(endDate));

What is the correct order of method calls to build the Mongo query I need?

8条回答
Anthone
2楼-- · 2020-02-17 06:59

This works on version 2.7.2 of the Java driver

DBCollection coll = db.getCollection("posts");  

BasicDBObject date = new BasicDBObject();
date.append("$gte", new Date(startDate));
date.append("$lte", new Date(endDate));

DBObject query = new BasicDBObject();
query.put("date", date);

DBCursor cursor = coll.find(query);

Also, for the record you have "startDate" for both the gte and the lte parameters.

查看更多
叛逆
3楼-- · 2020-02-17 07:02

You also can add query annotaion:

@Query("{'date' : { $gte: ?0, $lte: ?1 } }")                 
public List<AnyYourObj> getObjectByDate(Date from, Date to); 

Or proper spring data method signature:

public List<AnyYourObj> findByDateBetween(Date from, Date to);

Both of these approaches give the same result. You can read more here https://www.baeldung.com/queries-in-spring-data-mongodb and here https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/

查看更多
贼婆χ
4楼-- · 2020-02-17 07:04

I did like this

public interface PolicyRepository extends MongoRepository<Policy, String> {
    @Query("{'lastDate':{$gt:?0,$lt:?1}}")
        public List<Policy> findAllPolicies(Date today,Date somedate);
}
查看更多
Root(大扎)
5楼-- · 2020-02-17 07:05
public interface MyRepository extends MongoRepository<MyObject, MyObjectId> {

    List<MyObject> findByMydatefieldBetween(DateTime startDate, DateTime endDate);

}

https://docs.spring.io/spring-data/mongodb/docs/2.2.x-SNAPSHOT/reference/html/#mongodb.repositories.queries

查看更多
We Are One
6楼-- · 2020-02-17 07:08

Do not include the 'and("startDate")' part in your criteria.

Instead of :

query.addCriteria(Criteria.where("startDate").gte(startDate).and("startDate").lt(endDate));

You should use:

query.addCriteria(Criteria.where("startDate").gte(startDate).lt(endDate));

When you include the 'and("startDate")' part, Mongo see's it as two different entries on the same property.

查看更多
Anthone
7楼-- · 2020-02-17 07:09

I had to find dates between on field publishedDate and here is how I did it:

    Criteria publishedDateCriteria = Criteria
                        .where("publishedDateObject").gte(psDate)
                        .lte(peDate);
    Query query = new Query(publishedDateCriteria);
    mongoTemplate.find(query,
                        MyDocumentObject.class));
查看更多
登录 后发表回答