I'm using Spring data with mongodb. I have a collection called place :
{
"_id" : NumberLong(281469),
"_class" : "com.domain.Place",
"name" : "paris"
}
I want to get places starting with some String. In mongo console I could get the result using :
db.place.find({name : {$regex : /^par/, $options: 'i'}})
Using the spring data repositories I've tried this but always give an empty result:
@Query(value="{'name' : {$regex : ?0, $options: 'i'}}")
public Page<PlaceDetails> findByNameStartsWith(String name,Pageable pageable);
And in the call of the repository method, I make a concatenation this way :
repository.findByNameStartsWith("/^"+token+"/",new PageRequest(0,10));
while this repository method works :
@Query(value="{'name' : ?0}")
public Page<PlaceDetails> findByName(String name,Pageable pageable);
The class is declared this way :
@Document(collection="place")
public class PlaceDetails {
//...
}
Any idea why it doesn't work?
StartsWith
automatically applies the necessary wrapping into a regex, so with your client code you effectively wrap it twice. If you think about it: with your approach, the client effectively has to know that the starts-with clause is implement with a regex, which would be leaking internals.
So a simple:
repository.findByNameStartsWith(token, new PageRequest(0,10));
should do the trick.