简体   繁体   中英

Custom query regex MongoDB + Spring Data

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?

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

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

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