w3resource

How to use MongoDB's Like Query with Regex for Pattern Matching

MongoDB Pattern Matching: Using Regex for "Like" Queries

To query MongoDB with a "like" or similar function, you can use regular expressions (regex) within MongoDB’s query language. MongoDB does not have a direct SQL-style LIKE operator, but regex provides similar pattern-matching capabilities. Here’s a breakdown of how to achieve this, including syntax, example code, and an explanation.

Description:

In MongoDB, querying for documents that match partial strings is often needed when you're looking for data with specific text patterns. This can be achieved using regular expressions, which MongoDB supports with its $regex operator. Here’s how you can use $regex to emulate a "like" query, similar to SQL’s LIKE operator.

Syntax:

The basic syntax for a MongoDB "like" query using $regex is:

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

Explanation:

  • <field>: The name of the field you want to search.
  • $regex: Specifies the pattern you’re searching for.
  • pattern: The pattern to search, written as a regex.
  • $options: Optional. The i flag makes the search case-insensitive.

Example Code:

The following example queries a collection named products for all documents where the name field contains the substring "phone" (case-insensitive).

Code:

// Query the 'products' collection
db.products.find(
  {
    // Match documents where 'name' contains 'phone'
    name: {
      // Use the $regex operator for pattern matching
      $regex: /phone/,
      // 'i' option makes the search case-insensitive
      $options: 'i'
    }
  }
)

Explanation:

  • db.products.find(...)
    This command initiates a search query in the products collection.
  • { name: { $regex: /phone/, $options: 'i' } }
    Inside the find method, the query filters documents where the name field matches the specified pattern.
  • $regex: /phone/
    The $regex operator specifies the pattern, phone, as a regular expression.
  • $options: 'i'
    The i option makes the regex case-insensitive, allowing it to match "Phone," "PHONE," or "phone."

In this example, MongoDB will return all documents in the products collection where the name field contains the word "phone" in any 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/how-to-use-mongodb-like-query-for-pattern-matching.php