$regex

The `$regex` operator is used to perform pattern matching with regular expressions.

This operator is useful for querying string fields for matches that fit specific patterns. Common use cases include searching for documents where a field contains a substring, starts with a certain prefix, or matches a complex pattern.

Syntax

{
  "field": {
    $regex: /pattern/,
    $options: '<options>'
  }
}

Parameters

fieldstringrequired

The field in the document to apply the regular expression to. This should be a string field that you want to match against the provided pattern.

$regexpatternrequired

The regular expression pattern to match.

$optionsstring

Flags to modify the behavior of the regex. Common options include, but are not limited to `i` for case-insensitive matching, `m` for multiline matching, etc.

Examples

Sample Data

[
  {
    "_id": "00000000-0000-0000-0000-000000003001",
    "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury",
    "promotionEvents": [
      {
        "eventName": "Unbeatable Bargain Bash"
      },
      {
        "eventName": "Steal of a Deal Days"
      }
    ]
  },
  {
    "_id": "00000000-0000-0000-0000-000000003002",
    "name": "Fabrikam, Inc. | Home Accessory Outlet - West Adele",
    "promotionEvents": [
      {
        "eventName": "Incredible Discount Days"
      },
      {
        "eventName": "Steal of a Deal Days"
      }
    ],
    "location": {
      "lat": -89.2384,
      "lon": -46.4012
    }
  },
  {
    "_id": "00000000-0000-0000-0000-000000003003",
    "name": "Wide World Importers | Fitness Equipment Outlet - Reillyborough",
    "promotionEvents": [
      {
        "eventName": "Incredible Discount Days"
      }
    ],
    "location": {
      "lat": -2.4111,
      "lon": 72.1041
    }
  }
]

Find documents with a specific substring

Use the `$regex` operator to find all documents that match a specific pattern.

In this example, the operator filters to documents that contain the exact phrase `Home` in its name.

Query:

db.stores.find({ "name": { "$regex": /Home/ }}, { name: 1 })

Output:

[
  {
    _id: '00000000-0000-0000-0000-000000003001',
    name: 'Proseware, Inc. | Home Entertainment Hub - East Linwoodbury'
  },
  {
    _id: '00000000-0000-0000-0000-000000003002',
    name: 'Fabrikam, Inc. | Home Accessory Outlet - West Adele'
  }
]

Find documents using a case-insensitive match

The `$regex` operator includes options like case-insensitive search.

In this example, the operator filters to documents that contain the case-insensitive phrase `outlet` in its name.

Query:

db.stores.find({ "name": { $regex: /outlet/, $options: "i" }}, { name: 1 })

Output:

[
  {
    _id: '00000000-0000-0000-0000-000000003002',
    name: 'Fabrikam, Inc. | Home Accessory Outlet - West Adele'
  },
  {
    _id: '00000000-0000-0000-0000-000000003003',
    name: 'Wide World Importers | Fitness Equipment Outlet - Reillyborough'
  }
]

Related