Reputation: 333
I'm trying to write a "startsWith" query in Spring Data, using MongoDB. If I write this in Mongo shell, it works, lists every e-mail address starting with letter x or X (case insensitive): db.user.find({email:/^x/i})
However, this doesn't:
@Query(value = "{'$or':[{'name':?0},{'email':?0}]}")
List<User> findAllByFreeTextSearch(String keyword);
I tried to add the /^.../i to the keyword itself, and in a dozen combinations to the @Query but without luck. What is the correct syntax?
Upvotes: 1
Views: 4771
Reputation: 75914
/expression/ is alternative syntax used in shell & js drivers.
You need to pass "^x" as keyword for java driver.
Try
@Query(value = "{$or:[{name:{$regex:?0,$options:'i'}},{email:{$regex:?0,$options:'i'}}]}")
List<User> findAllByFreeTextSearch(String keyword);
Upvotes: 4
Reputation: 6726
Spring Data wraps those parameters by intent to prevent malicious patterns from being executed via an annotated query.
Please use $regex
like below for that.
@Query("{'$or':[{ 'name' : { '$regex' : '?0', '$options' : 'i'}}, ...")
List<User> findAllByFreeTextSearch(String keyword);
Upvotes: 2