How to Query MongoDB with “like”?
To query MongoDB with a “like” operator equivalent, we can use the $regex operator along with regular expressions. However, MongoDB offers several methods to query MongoDB with “like” are defined below:
- Using $regex Expressions
- Using the Regular Operator
Syntax:
db.collection.find({ "field": { $regex: /pattern/i } });
- collection: The name of the MongoDB collection we want to query.
- “field”: The field within the documents we want to query.
- /pattern/: The regular expression pattern we want to match.
- i: An optional flag that makes the pattern case-insensitive.
Let’s set up an Environment:
To understand How to query MongoDB with “like” we need a collection and some documents on which we will perform various operations and queries. Here we will consider a collection called users which contains information like name, email, username, bio, and city of the Employees in various documents.
> db.users.insertMany([
{
"name": "John Doe",
"email": "john@example.com",
"username": "johndoe",
"bio": "Software Engineer with a passion for coding",
"city": "New York"
},
{
"name": "Alice Smith",
"email": "alice@example.com",
"username": "alicesmith",
"bio": "Web Developer interested in UX design",
"city": "San Francisco"
},
{
"name": "francis",
"email": "francis@example.com",
"username": "francis",
"bio": "data scientist",
"city": "Madagascar"
}
]);
Output:
How to Query MongoDB with “like”?
Querying data in MongoDB often requires pattern–matching operations similar to SQL’s “LIKE” operator. While MongoDB doesn’t have a direct “LIKE” operator, it offers the $regex operator and regular expressions for achieving similar functionality.
In this article, We will learn about How to Query MongoDB with “like” with the help of $regex and regular expression in detail along with the implementations and so on.