简体   繁体   中英

Date range query on ObjectId in MongoDB using Spring REST pagination

I need to do a date range query in the users collection. However it does not have a date field. I found some useful resources to convert time to ObjectId first then query on it in Mongodb shell:

>var idMin = ObjectId(Math.floor((new Date('2018/1/1'))/1000).toString(16) + "0000000000000000")
>var idMax = ObjectId(Math.floor((new Date('2018/2/1'))/1000).toString(16) + "0000000000000000")
>db.users.find({_id:{$gt: idMin, $lt: idMax}})

My project will get the time range at frontend, convert it to ObjectId string (idMin, idMax) then make a request to Spring REST API to fetch the data. How can I implement the query using Spring with pageable? Is there an ObjectId class in spring mongodb lib?

User.java:

@Document(collection = "users")
    public class User {

    @Id
    private String id;

    private String name;

    private int age;
}

UserRepository.java

@RequestMapping(path = "/users/{idMin}/{idMax}", method = RequestMethod.GET)
public interface UserRepository extends MongoRepository<User, String> {

    Page<User> findAll(Pageable pageable);

    //TODO: query on id range {idMin, idMax}
}

You can try something like

Calling Code:

ObjectId idMin = new ObjectId(new Date("2018/1/1"));
ObjectId idMax = new ObjectId(new Date("2018/2/1"));
Pageable pages = new PageRequest(1, 2);

Page<User> results = repository.findByObjectIdsAndPages(idMin, idMax, pages);

Repository

 @Query("{_id:{$gt: ?0, $lt: ?1}}")
 Page<User> findByObjectIdsAndPages(ObjectId idMin, ObjectId idMax, Pageable pages);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM