MongoDB:基于test集合使用正则表达式实现文本搜索的方法
test Collection Based on your sample data, here are practical, straightforward ways to perform regex-based text searches on your test collection, covering common use cases you might need:
Basic Substring Search
If you just need to find documents where a field contains a specific substring (like looking for "vn" in the __key field), you can use MongoDB's native regex support directly in your query:
// Find all documents where __key includes "vn" db.test.find({ __key: /vn/ })
This will return the first two documents in your sample since their __key values have "vn1" and "vn2".
Case-Insensitive Search
To ignore uppercase/lowercase differences in your search, add the i flag to the regex:
// Case-insensitive search for "VN" or "vn" db.test.find({ __key: /vn/i })
Targeted Pattern Matches
For more precise searches, use regex anchors and quantifiers to narrow down results:
- Starts with a specific string: Use
^to anchor to the start of the field// Find documents where __key starts with "default-domain" db.test.find({ __key: /^default-domain/ }) - Ends with a specific pattern: Use
$to anchor to the end of the field// Find documents where __key ends with a letter followed by a digit (like "c6", "c7") db.test.find({ __key: /[a-z]\d$/ }) - Match exact segments in semicolon-separated values: If you want to find documents where
__keyhas an exact segment (like "a0" in "a0;b0;c0") without partial matches, use this pattern:// Find documents where __key contains the exact segment "a0" db.test.find({ __key: /(^|;)a0(;|$)/ })
Performance Optimization Tip
If you're running frequent text searches on large datasets, consider creating a text index for faster queries (note: text indexes work best for word-based searches, not complex regex patterns):
// Create a text index on the __key field db.test.createIndex({ __key: "text" }) // Use the $text operator to search for keywords db.test.find({ $text: { $search: "vn1" } })
Text indexes speed up searches for whole words, but if you need complex regex patterns (like partial matches or segment-specific checks), stick to the direct regex queries above. A quick note: Regex queries that don't start with an anchor (^) will scan all documents in the collection, so use anchored patterns whenever possible to leverage existing indexes and boost performance.
内容的提问来源于stack exchange,提问作者u_peerless

