w3resource

Using MongoDB to check if a field contains a Substring

Check if a field contains a string in MongoDB

To check if a field contains a specific substring in MongoDB, you can use the $regex operator to perform pattern matching on string fields. This allows you to search for documents where a field includes a specified substring. Here’s how to do it, including syntax, example code, and an explanation

Description:

In MongoDB, checking if a field contains a particular substring can be done using the $regex operator. This operator matches the specified pattern within a string field, similar to searching for text within a field. The $regex operator is flexible and can be case-insensitive, making it a powerful tool for text searches.

Syntax:

The syntax for querying if a field contains a string is:

{ <field>: { $regex: /substring/, $options: 'i' } }

Explanation:

  • <field>: The field you want to search within.
  • $regex: Specifies the substring or pattern to look for.
  • substring: The specific text or substring you want to find within the field.
  • $options: 'i': (Optional) Makes the search case-insensitive.

Example Code:

Here's an example that queries a products collection for all documents where the description field contains the word "wireless" (case-insensitive).

Code:

// Query the 'products' collection
db.products.find(
  {
    // Check if 'description' contains the substring 'wireless'
    description: {
      // Use the $regex operator to search for 'wireless'
      $regex: /wireless/,
      // 'i' option makes the search case-insensitive
      $options: 'i'
    }
  }
)

Explanation:

  • db.products.find(...)
    This command begins a query on the products collection.
  • { description: { $regex: /wireless/, $options: 'i' } }
    This query filters for documents where the description field includes the substring "wireless," regardless of case.
  • $regex: /wireless/
    The $regex operator specifies the substring "wireless" as the pattern to search for.
  • $options: 'i'
    This option makes the search case-insensitive, meaning it will match "Wireless," "WIRELESS," or "wireless."

In this example, MongoDB will return all documents in the products collection where the description field contains the word "wireless" in any letter case.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/mongodb/snippets/check-if-a-field-contains-a-string-in-mongodb.php