Mongodb + Java Drivers. Search by date range

前端 未结 4 1827
眼角桃花
眼角桃花 2020-12-18 07:03

This is my first shot at using Mongodb with the java drivers. I can query the database via command line using javascript and the Date() object, however, I am having trouble

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-18 07:33

    Based on the query that was output, you are looking for a document with a field created_on that also has a child named created_on. I assume no such document exists. In other words, you query is not correctly formed.

    Your query object should look like this:

    BasicDBObject dateRange = new BasicDBObject ("$gte", new Date(current.getYear(), current.getMonth(), current.getDate());
    dateRange.put("$lt", new Date(current.getYear(), current.getMonth() - 1, current.getDate());
    
    BasicDBObject query = new BasicDBObject("created_on", dateRange);
    

    Also, as a sidebar, you probably should avoid using the three-argument constructor of the java.util.Date class, as it is deprecated. When working with dates in the MongoDB Java driver, I typically use the java.util.Calendar class, and its getTime() method.

提交回复
热议问题