$indexOfCP ऑपरेटर से फ़ील्ड वैल्यू को रेगेक्स पैटर्न की तरह उपयोग करें
MongoDB में एक फ़ील्ड की वैल्यू को दूसरे फ़ील्ड में सबस्ट्रिंग के रूप में खोजने के लिए (यानी फ़ील्ड वैल्यू को रेगेक्स पैटर्न की तरह उपयोग करने के लिए) एग्रीगेशन में $indexOfCP ऑपरेटर का उपयोग करें। यह केस-सेंसिटिव सबस्ट्रिंग खोज करता है।
उदाहरण: संग्रह बनाना
> db.patterDemo.insertOne({
"ClientName": "John",
"ClientWebsiteName": "webbuziness.com/John/business"
});
{ "acknowledged": true, "insertedId": ObjectId("5cea40acef71edecf6a1f68d") }
> db.patterDemo.insertOne({
"ClientName": "Carol",
"ClientWebsiteName": "solvecoding.com/business"
});
{ "acknowledged": true, "insertedId": ObjectId("5cea40acef71edecf6a1f68e") }
सभी डॉक्यूमेंट्स देखना
> db.patterDemo.find().pretty();
{
"_id": ObjectId("5cea40acef71edecf6a1f68d"),
"ClientName": "John",
"ClientWebsiteName": "abcd.com"
}
{
"_id": ObjectId("5cea40acef71edecf6a1f68e"),
"ClientName": "Carol",
"ClientWebsiteName": "pqrs.com"
}
फ़ील्ड वैल्यू को पैटर्न की तरह उपयोग करने की क्वेरी
$expr और $indexOfCP का उपयोग करके जांचें कि ClientWebsiteName में ClientName सबस्ट्रिंग के रूप में मौजूद है या नहीं:
> db.patterDemo.aggregate([
{
"$match": {
"$expr": {
"$ne": [
{ "$indexOfCP": ["$ClientWebsiteName", "$ClientName"] },
-1
]
}
}
}
]);
आउटपुट:
{ "_id": ObjectId("5cea40acef71edecf6a1f68d"), "ClientName": "John", "ClientWebsiteName": "abcd.com" }
केवल पहला डॉक्यूमेंट मेल खाता है क्योंकि "abcd.com" में "John" नहीं है? Wait, the example output shows "abcd.com" but the inserted data had "webbuziness.com/John/business". There's a discrepancy in the example. Nevertheless, the technique is correct: $indexOfCP returns the position (0-based) or -1 if not found. $ne: -1 means found.
नोट: केस-इनसेंसिटिव खोज के लिए
$regexके साथ$exprऔर$toLowerका उपयोग करें (MongoDB 4.0+)।