繁体   English   中英

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

[英]Using lambda function in MongoDB $where clause in Java

我正在尝试使用 $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()) }
}
)

weekdaytimeOffset是文档字段。 这个查询在 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中完成查询?

预先感谢您的帮助!

好的,

我已经为相同的查询找到了替代解决方案。 由于以下 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()");

它对我来说非常有效!

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");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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