Tutorialspoint

1 Answer
Smita Kapse

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

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.