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" }

Updated on: 30-Jul-2019

134 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements