How to perform wildcard search in MongoDB using Java

寵の児 提交于 2020-01-05 05:56:10

问题


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!


回答1:


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


来源:https://stackoverflow.com/questions/11552976/how-to-perform-wildcard-search-in-mongodb-using-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!