Scott Esker
Scott Esker

Reputation: 11

Writing LIKE equivalent queries in Spring mongoTemplates.. or what should I use?

I am using spring and the MongoTemplate and trying to write an equivalent query SQL LIKE statement.. I am have not seen a satisfactory answer, code below:

@Document
public class Lake {
@Id
private String oid;
@Indexed (sparse = true)
private String name;
private String state;
}


public List<Lake> listLakesLike(String likename) {
try {
    Query filter = new Query(Criteria.where("name").regex("lakename","i"));
    List<Lake> lakes = mongoTemplate.find(filter, Lake.class);
    return lakes
}  

I saw this as an example that DOES NOT work, no lakes returned.

How do I write a mongoTemplate.find that results in matching LIKE lake names based on the passed in value likename?

Thank you in advance.. This is driving me crazy.. Or if you can point me to an example.

Upvotes: 1

Views: 2742

Answers (1)

gerrytan
gerrytan

Reputation: 41143

Spring MongoDB syntax

Query filter = new Query(Criteria.where("name").regex("lakename","i"));

Is equivalent to MongoDB shell command

db.lake.find({name:/lakename/i})

Notice in spring leading and trailing slashes are not required. Try the command first in your shell to check you have all the data correct, if it doesn't work I'm pretty sure your problem lies elsewhere (eg: your Spring MongoDB is pointing to a wrong host / database.collection name)

Also notice Spring MongoDB implicitly converts the class name Lake into collection name lake (with lowercase). If you need to specify explicit collection name you can do so using @Document(collection = "Lake")

Upvotes: 5

Related Questions