How to perform wildcard search in MongoDB using Java

I am just getting to use MongoDB! Was trying out with variety of search features supported here.

I could search for a document, say containing name=MongoDB with the following options (irrespective of the case) - goDB, Mongo, go. Working out to search for the document in the following options - Mon*DB, *on*DB. That is, having multiple wild-card in the same search text.

Any pointers would be appreciated!

Upvotes: 1

Views: 4569

Answers (1)

MrKurt
MrKurt

Reputation: 5100

You can do a Regular expression match on fields in Mongo, here's how you'd do the first of your patterns:

Pattern p = Pattern.compile("Mon.*DB", CASE_INSENSITIVE);
BasicDBObject query = new BasicDBObject("name", p);

// finds all records with "name" matching /Mon.*DB/i
DBCursor cursor = collection.find(query);

Be careful, though, many regular expression matches require a full table scan. This means that if you run them against a large collection, the engine will have to iterate over all the documents (probably hitting disk) and check each individually for a match. This is much slower than queries that use indexes.

The only regular expressions that will hit an index are case sensitive prefix matches. You could search for all "Mon*" like this and use an index:

Pattern p = Pattern.compile("^Mon.*");
BasicDBObject query = new BasicDBObject("name", p);

// finds all records with "name" matching /^Mon.*/
DBCursor cursor = collection.find(query);

Upvotes: 6

Related Questions