Welcome to plsql4all.blogspot.com SQL, MYSQL, ORACLE, TERADATA, MONGODB, MARIADB, GREENPLUM, DB2, POSTGRESQL.

Wednesday 21 February 2024

REGEXP Function in MongoDB

In MongoDB, you can use the $regex operator to perform regular expression matching within a query. Here's an example:


Suppose you have a collection named products with documents containing a field named product_name, and you want to find all products whose names start with "Apple":


db.products.find({ product_name: { $regex: /^Apple/ } })


In this example:

- products is the collection containing product documents.

- product_name is the field within each document that holds the product name.

- $regex is the operator used to perform regular expression matching.

- /^Apple/ is the regular expression pattern. The ^ asserts the start of the string, so it matches product names that start with "Apple".


This query will return all documents from the products collection where the product_name field starts with "Apple".


You can adjust the regular expression pattern to match different patterns according to your requirements. For example, to match any product name containing "Apple" anywhere in the string, you could use { $regex: /Apple/ }.

No comments:

Post a Comment

Please provide your feedback in the comments section above. Please don't forget to follow.