MongoDB में पैटर्न मिलान के लिए $regex ऑपरेटर का उपयोग करें। यह केस-सेंसिटिव और केस-इनसेंसिटिव दोनों खोज का समर्थन करता है।
सिंटैक्स
db.yourCollectionName.find({yourFieldName: {$regex: yourValue}});
उदाहरण
विभिन्न केस में नाम वाले दस्तावेज़ बनाएं:
> db.regularExpressionDemo.insertOne({"UserName": "John"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cdffc25bf3115999ed51210") }
> db.regularExpressionDemo.insertOne({"UserName": "JOHN"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cdffc2ebf3115999ed51211") }
> db.regularExpressionDemo.insertOne({"UserName": "john"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cdffc35bf3115999ed51212") }
> db.regularExpressionDemo.insertOne({"UserName": "JoHn"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cdffc3ebf3115999ed51213") }
सभी दस्तावेज़ देखें:
> db.regularExpressionDemo.find();
{ "_id" : ObjectId("5cdffc25bf3115999ed51210"), "UserName" : "John" }
{ "_id" : ObjectId("5cdffc2ebf3115999ed51211"), "UserName" : "JOHN" }
{ "_id" : ObjectId("5cdffc35bf3115999ed51212"), "UserName" : "john" }
{ "_id" : ObjectId("5cdffc3ebf3115999ed51213"), "UserName" : "JoHn" }
केस-सेंसिटिव खोज: "JOHN"
> db.regularExpressionDemo.find({'UserName': {$regex: 'JOHN'}});
{ "_id" : ObjectId("5cdffc2ebf3115999ed51211"), "UserName" : "JOHN" }
केस-इनसेंसिटिव खोज: सभी वेरिएंट (i विकल्प)
> db.regularExpressionDemo.find({'UserName': {$regex: 'JOHN', $options: 'i'}});
{ "_id" : ObjectId("5cdffc25bf3115999ed51210"), "UserName" : "John" }
{ "_id" : ObjectId("5cdffc2ebf3115999ed51211"), "UserName" : "JOHN" }
{ "_id" : ObjectId("5cdffc35bf3115999ed51212"), "UserName" : "john" }
{ "_id" : ObjectId("5cdffc3ebf3115999ed51213"), "UserName" : "JoHn" }
रेगुलर एक्सप्रेशन विकल्प
| विकल्प | नाम | विवरण |
|---|---|---|
i | केस-इनसेंसिटिव | बड़े/छोटे अक्षर अनदेखा |
m | मल्टीलाइन | ^ और $ लाइन ब्रेक से मेल |
x | एक्सटेंडेड | व्हाइटस्पेस अनदेखा, टिप्पणी अनुमति |
s | सिंगल लाइन | . न्यूलाइन से भी मेल |