shimrit shimrit - 6 months ago 41
Java Question

MongoTemplate - where with JS function

I need to query the db with the $where operator from Java Spring mongoTemplate.
This is the query:

db.myCollection.find( {$where : function () {
for (var index in this.*someKey*){
if (index.indexOf(*someValue*) > -1){
return this;
}
}
}})


But the mongoTemplate where operator expects to receive key not java script string function. Is there anyway around this?

Answer

I ended up using Spring MongoDB repositories(I needed paging as well)

public interface MyCollectionRepository extends PagingAndSortingRepository<MyCollectionClass, String> {
    @Query("{$where : ?0}")
    Page<MyCollectionClass> findSomething(String whereQuery, Pageable pageable);

     .....
}

And

 public static String whereQuery(String someValue){
        return "function() {" +
                    "for (var index in this.*someKey*){" +
                        "if (index.indexOf(\""+ someValue+"\") > -1){" +
                          "return this;" +
                         "}" +
                     "}" +
                "}";
    }