在Java中使用MongoDB $ where子句中的lambda函数

时间:2015-07-29 19:07:52

标签: javascript java mongodb lambda

我正在尝试使用$ where子句在Java中执行JavaScript等效查询。 JavaScript查询如下所示:

var currDate = new ISODate()
db.getCollection('rides')
.find(
{
        "startDate" : {
            "$lte" : currDate
        },
        "stopDate" : {
            "$gte" : currDate
         },
        $where : function() { return (this.weekday == new Date(new ISODate().getTime() + this.timeOffset).getDay()) }
}
)

工作日 timeOffset 是文档字段。 这个查询在MongoDB shell中运行得很好。我试图找到一种在Java 8中编写此查询的方法。 我尝试了以下内容:

BasicDBObject query =  new BasicDBObject("stopDate",new BasicDBObject("$gte", currDate))
                .append("startDate",new BasicDBObject("$lte", currDate))
                .append("weekday",
                        new BasicDBObject("$where", () ->
                        {
                            return (this.weekday == currDate + this.timeOffset)
                        }));

但是我甚至无法编译此代码。 Java 无法识别。 有没有办法在Java中完成查询?

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

确定,

我已经找到了针对同一查询的替代解决方案。由于以下Javascript查询等同于发布的查询:

var currDate = new ISODate()
db.getCollection('rides')
.find(
{
    "startDate" : {
        "$lte" : currDate
    },
    "stopDate" : {
        "$gte" : currDate
     },
    $where : 'this.weekday == new Date(new Date().getTime() + this.timeOffset).getDay()'
})

我可以用Java编写相同的内容:

BasicDBObject query =  new BasicDBObject("stopDate",new BasicDBObject("$gte", currDate))
            .append("startDate", new BasicDBObject("$lte", currDate))
            .append("$where", "this.weekday == new Date(new Date().getTime() + this.timeOffset).getDay()");

它对我来说非常有用!

答案 1 :(得分:0)

Document whereDoc = new Document(
    "$where",
    "function(){var j=false; [2,4].forEach(i=>{if([4,5].indexOf(i)>-1){j=true;}}); return j;}"
);

Query query = new BasicQuery(whereDoc);
query.addCriteria(Criteria.where("ent_id").is("google"));
query.addCriteria(Criteria.where("app_id").is("pic"));
List<Map> result = mongoTemplate.find(query, Map.class, "googletest");
相关问题