Regex का उपयोग
$regex pattern searches के लिए strings को regular expressions के against match करता है।
In this page:
Syntax
{ field: /pattern/ }
{ field: { $regex: "pattern", $options: "i" } }
Regex
Case-insensitive matching के लिए { field: /pattern/ } या { $regex: "pattern", $options: "i" } इस्तेमाल करें। /^abc/ जैसे anchored, case-sensitive prefix patterns एक index efficiently इस्तेमाल कर सकते हैं; unanchored वाले scan करते हैं।
Real text search के लिए इसकी बजाय एक text index या Atlas Search इस्तेमाल करें।
Note:
indexes का फायदा लेने के लिए ^ से patterns anchor करें।
उदाहरण: Regex
test> db.people.insertMany([{ _id: 1, name: "Ada" }, { _id: 2, name: "adam" }, { _id: 3, name: "Bob" }, { _id: 4, name: "Nadia" }])
{
acknowledged: true,
insertedIds: { '0': 1, '1': 2, '2': 3, '3': 4 }
}
test> db.people.find({ name: /^ad/i }, { _id: 0 })
[ { name: 'Ada' }, { name: 'adam' } ]
test> db.people.find({ name: { $regex: "a$" } }, { _id: 0 })
[ { name: 'Ada' }, { name: 'Nadia' } ]
test> db.people.find({ name: /^Ad/ }, { _id: 0 })
[ { name: 'Ada' } ]
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- बड़ी collections पर unanchored regex इस्तेमाल करना
- i option भूल जाना
- user input को unescaped एक regex में pass करना
चैप्टर सारांश
- /pattern/ या options के साथ $regex
- i इसे case-insensitive बनाता है
- Anchored prefixes indexes इस्तेमाल करते हैं
- User input escape करें
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: