user1479897
user1479897

Reputation: 145

Morphia mongoDB wildcard query

Straight forward question, does anybody know how to make a wildcard query using morphia linked to a mongoDB database?

This is what the mongo statement would look like:

Mongo: db.users.find({name:/Joe/})
SQL: SELECT * FROM users WHERE name LIKE "%Joe%"

My morphia statement looks like:

Morphia: ds.find(File.class, "filename","/test/").order("filename").asList();

I have filenames in my database such as test1, test etc

If someone could please tell me if it's even possible with morphia it would be most appreciated.

Thanks

Upvotes: 7

Views: 5347

Answers (3)

Ali Saeed
Ali Saeed

Reputation: 1569

Can also do:

ds.createQuery(File.class)
    .criteria("filename").contains("test")
    .asList();

Upvotes: 3

Indrajeet
Indrajeet

Reputation: 647

This will also work

DS.find(Model.class).field("filename").startsWithIgnoreCase("name").asList();

Upvotes: 2

Philipp
Philipp

Reputation: 69663

What you refer to as a "wildcard" is in fact a "Regular Expression".

The Java class which represents regular expressions is the Pattern. You can pass these to the filter method of Morphia's Query object.

// create a regular expression which matches any string which includes "test"
Pattern regexp = Pattern.compile("test");
// use this regular expression to create a query
Query q = ds.createQuery(File.class).filter("filename", regexp).sort("filename");

Upvotes: 20

Related Questions