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

Yes, you can use a MongoDB field value as a pattern in $regex using the $expr operator. However, the most practical approach is using $indexOfCP to check if one field value exists within another field.

Syntax

db.collection.aggregate([
    {
        "$match": {
            "$expr": {
                "$ne": [
                    { "$indexOfCP": ["$fieldToSearch", "$patternField"] },
                    -1
                ]
            }
        }
    }
])

Sample Data

db.demo88.insertMany([
    {
        "Name": "Chris",
        "PassoutYear": "2020",
        "websiteName": "chris.shop.com/Carol-2020-"
    },
    {
        "Name": "David",
        "PassoutYear": "2010",
        "websiteName": "david.bigshop.com/David-2010-"
    }
]);
{
    "acknowledged": true,
    "insertedIds": {
        "0": ObjectId("5e2c14c471bf0181ecc422b1"),
        "1": ObjectId("5e2c14c571bf0181ecc422b2")
    }
}

Example: Field Value as Pattern

Find documents where the Name field value exists within the websiteName field ?

db.demo88.aggregate([
    {
        "$match": {
            "$expr": {
                "$ne": [
                    { "$indexOfCP": ["$websiteName", "$Name"] },
                    -1
                ]
            }
        }
    }
])
{ "_id": ObjectId("5e2c14c571bf0181ecc422b2"), "Name": "David", "PassoutYear": "2010", "websiteName": "david.bigshop.com/David-2010-" }

How It Works

  • $indexOfCP searches for the Name field value within the websiteName field
  • Returns the index position if found, or -1 if not found
  • $ne: -1 filters documents where the pattern was found (index ? -1)
  • Only "David" matches because "David" exists in "david.bigshop.com/David-2010-"

Conclusion

While MongoDB doesn't directly support field values in $regex, $indexOfCP with $expr provides an effective alternative for pattern matching using field values. This approach is more efficient than complex regex operations.

Updated on: 2026-03-15T01:52:53+05:30

164 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements