如何使用 Java 在 MongoDB 中执行通配符搜索 [英] How to perform wildcard search in MongoDB using Java
问题描述
我刚刚开始使用 MongoDB!正在尝试使用此处支持的各种搜索功能.
I am just getting to use MongoDB! Was trying out with variety of search features supported here.
我可以使用以下选项(不考虑大小写)搜索包含 name=MongoDB 的文档 - goDB、Mongo、go.努力在以下选项中搜索文档 - Mon*DB、*on*DB.也就是说,在同一个搜索文本中有多个通配符.
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.
任何指针将不胜感激!
推荐答案
你可以做一个 正则表达式匹配 Mongo 中的字段,以下是您如何执行第一个模式:
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.
唯一会命中索引的正则表达式是区分大小写的前缀匹配.您可以像这样搜索所有Mon*"并使用索引:
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);
这篇关于如何使用 Java 在 MongoDB 中执行通配符搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!