[英]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()) }
}
)
而weekday和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中完成查詢?
預先感謝您的幫助!
好的,
我已經為相同的查詢找到了替代解決方案。 由於以下 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.