Is it possible to use MongoDB field value as a pattern in $regex?


Yes, you can use $indexOfCP to use a filed value as a pattern. Let us create a collection with documents −

> db.demo88.insertOne(
...    {
...       "Name": "Chris",
...       "PassoutYear": "2020",
...       "websiteName": "chris.shop.com/Carol-2020-"
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2c14c471bf0181ecc422b1")
}
> db.demo88.insertOne(
...    {
...       "Name": "David",
...       "PassoutYear": "2010",
...       "websiteName": "david.bigshop.com/David-2010-"
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2c14c571bf0181ecc422b2")
}

Display all documents from a collection with the help of find() method −

> db.demo88.find();

This will produce the following output −

{ "_id" : ObjectId("5e2c14c471bf0181ecc422b1"), "Name" : "Chris", "PassoutYear" : "2020", "websiteName" : "chris.shop.com/Carol-2020-" }
{ "_id" : ObjectId("5e2c14c571bf0181ecc422b2"), "Name" : "David", "PassoutYear" : "2010", "websiteName" : "david.bigshop.com/David-2010-" }

Following is the query to use field value as pattern in $regex −

> db.demo88.aggregate([ { "$match": { "$expr": { "$ne": [ { "$indexOfCP": ["$websiteName", "$Name"] }, -1 ] } }} ])

This will produce the following output −

{ "_id" : ObjectId("5e2c14c571bf0181ecc422b2"), "Name" : "David", "PassoutYear" : "2010", "websiteName" : "david.bigshop.com/David-2010-" }

Updated on: 30-Mar-2020

58 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements