mongoDB查询到Java代码[$和lte和gte的条件]

时间:2017-03-15 12:14:17

标签: java mongodb

如何为以下MongoDB查询编写Java代码

db.getCollection('testing')
      .find({"Mid" : "652ba8c0", 
             "sname" : "biole", 
             "timeVal" : { $gte : ISODate("2017-03-14T13:40:39.117Z")
                        , $lte : ISODate("2017-03-14T14:30:12.419Z")}
            })
      .sort({"timeVal" : -1})

我尝试编写如下,但它不会获取任何记录,而是应该获取可用记录(对于上面的MongoDB查询,它会获取200条记录)

dbCollection.find(Filters.and(Filters.eq("XDK", engno),
                              Filters.eq("sensorName", sensor),
                              Filters.gte("timestamp", startMinusDate),
                              Filters.lte("timestamp", startPlusDate)))
             .sort(new BasicDBObject("timestamp", 1));

dbCollection.find(Filters.and(Filters.eq("XDK", engno),
                              Filters.eq("sensorName", sensor),
                              Filters.and(Filters.gte("timestamp", startMinusDate), 
                                          Filters.lte("timestamp", startPlusDate))))
            .sort(new BasicDBObject("timestamp", 1));

我在jar文件下使用

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.3.0</version>
</dependency>

1 个答案:

答案 0 :(得分:1)

对于MongoDB Java驱动程序;

Document document = new Document();
document.append("Mid" , "652ba8c0").append("sname" , "biole");
document.append("timeVal" , new Document().append("$gte", startMinusDate).append("$lte", startPlusDate));
collection.find(document).sort(new Document().append("timeVal", -1));