简体   繁体   中英

Using lambda function in MongoDB $where clause in Java

I'm trying to execute JavaScript equivalent query in Java using the $where clause. The JavaScript query looks like this:

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()) }
}
)

While weekday and timeOffset are document fields. This query works just fine in MongoDB shell. I'm trying to find out a way to write this query in Java 8. I've tried the following:

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

However I can't even compile this code. Java this is not recognized. Is there a way to accomplish the query in Java?

Thanks in advance for help!

Ok,

I've figured out an alternative solution for the same query. Since the following Javascript query is equivalent to the posted one:

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()'
})

I could just write the same in 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()");

And it perfectly worked for me!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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