2

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!

2 Answers 2

1

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!

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Answers are usually more helpful if you can explain what you did and why instead of just pasting a wall of code. Also this doesn't really look like the query that was asked about (there are no dates and other fields are being queried on).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.