Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Is it possible to use MongoDB field value as pattern in $regex?
Yes, for this, use $indexOfCP operator along with aggregate framework. Let us first create a collection with documents −
> 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")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.patterDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5cea40acef71edecf6a1f68d"),
"ClientName" : "John",
"ClientWebsiteName" : "abcd.com"
}
{
"_id" : ObjectId("5cea40acef71edecf6a1f68e"),
"ClientName" : "Carol",
"ClientWebsiteName" : "pqrs.com"
}
Following is the query to use field value as pattern in $regex −
> db.patterDemo.aggregate([ { "$match": { "$expr": { "$ne": [ { "$indexOfCP": ["$ClientWebsiteName", "$ClientName"] }, -1 ] } }} ]);
This will produce the following output −
{ "_id" : ObjectId("5cea40acef71edecf6a1f68d"), "ClientName" : "John", "ClientWebsiteName" : "abcd.com" }Advertisements