How to Query MongoDB with "like"?
Last Updated :
10 Apr, 2024
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.
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": "[email protected]",
"username": "johndoe",
"bio": "Software Engineer with a passion for coding",
"city": "New York"
},
{
"name": "Alice Smith",
"email": "[email protected]",
"username": "alicesmith",
"bio": "Web Developer interested in UX design",
"city": "San Francisco"
},
{
"name": "francis",
"email": "[email protected]",
"username": "francis",
"bio": "data scientist",
"city": "Madagascar"
}
]);
Output:
user collections created1. Using the $regex Operator
In MongoDB, the $regex operator is a powerful tool for performing pattern matching operations within queries. It allows for flexible searching based on regular expressions, enabling refined search capabilities similar to SQL's "LIKE" operator.
Example 1
Let's Retrieve documents from the "users" collection where the "name" field contains the case-insensitive string "john".
// Querying the documents where name contains with John
db.users.find({ "name": { $regex: /john/i } });
Output:
Querying MongoDB with "like"Explanation: In the above output, we quered all the documents where name contains with "john".
Example 2
Let's Find all documents in the "users" collection where the "username" field contains the case-insensitive string "alice"
// Querying the documents where username contains alice
db.users.find({ "username": { $regex: /alice/i } });
Output:
Querying MongoDB with "like"Explanation: In the above output, we quered all the documents where username contains "alice".
2. Using Regular Expressions
In MongoDB, Regular Expressions (regex) offer a powerful tool for querying and searching data based on specific patterns within fields. Regular expressions allow for flexible and dynamic searches, akin to SQL's "LIKE" operator.
Example 1:
Let's Retrieve documents from the "users" collection where the "bio" field contains the case-insensitive substring "data"
// Find documents where the bio contains "data" (case insensitive)
db.users.find({ bio: { $regex: /data/, $options: 'i' } })
Output:
Querying MongoDB with "like"Explanation: In the above output, we quered all the documents where username contains "alice".
Example 2
Let's Retrieve documents from the "users" collection where the "email" field contains the substring "john" using a multi-line matching pattern.
// Find documents where the email contains "john"
db.users.find({ email: { $regex: /john/, $options: 'm' } })
Output:
Querying MongoDB with "like"Explanation: In the above output, we quered all the documents where the email contains "john".
Conclusion
Overall, Querying MongoDB with "like" operators is a powerful feature provided by MongoDB's $regex operator and regular expressions. With the help of these features, you can perform flexible and dynamic searches within your MongoDB collections, enhancing your data querying capabilities.
Similar Reads
What is a MongoDB Query?
A MongoDB query is a request to the database to retrieve specific documents or data based on certain conditions or criteria. It is similar to SQL queries in traditional relational databases, but MongoDB queries are written using JavaScript-like syntax. The most common query operation in MongoDB is t
10 min read
How to Use $unwind Operator in MongoDB?
MongoDB $unwind operator is an essential tool for handling arrays within documents. It helps deconstruct arrays, converting each array element into a separate document, which simplifies querying, filtering, and aggregation in MongoDB. By understanding the MongoDB $unwind syntax users can utilize thi
6 min read
MongoDB Query with Case Insensitive Search
In MongoDB, case-insensitive queries are essential for retrieving data without being affected by letter casing. This feature allows developers to search for documents without worrying about whether the input is in uppercase or lowercase. One effective way to implement this is through the MongoDB $re
5 min read
MongoDB Query to Find Records with Keys Containing Dots
In MongoDB, field names (or keys) in documents are strings that uniquely identify values stored within those documents. While MongoDB allows field names to contain dots (e.g., "user.name"), using keys with dots can be challenging when querying documents due to the way MongoDB interprets dots in quer
4 min read
How to Search by id in MongoDB
In MongoDB, each document in a collection is uniquely identified by a field called "_id". This "_id" field serves as the primary key and provides a unique identifier for each document. Searching by ID is a common operation in MongoDB and allows us to retrieve specific documents based on their unique
4 min read
How to Make a Synchronous MongoDB Query in NodeJS?
MongoDB is a popular NoSQL database that is often used in modern web development. It is known for its flexibility, scalability, and ease of use. Node.js, with its non-blocking, event-driven architecture, is a natural fit for MongoDB. However, working with asynchronous code can sometimes be challengi
2 min read
How to Install MongoDB to WAMP?
Everyone has heard about Mongo DB. MongoDB is an open-source tool that supports NoSQL. It is document-oriented not object-oriented. MongoDB is usually used when large data is set to manage information. Here we discuss the installation of MongoDB on Wamp. Before we know about what is Mongo DB and its
2 min read
How to Filter Array in Subdocument with MongoDB?
In MongoDB, working with arrays within subdocuments is a common requirement in many applications. Filtering and manipulating arrays efficiently can significantly enhance the flexibility and enhance our queries. In this article, we'll explore how to filter arrays within subdocuments in MongoDB by cov
5 min read
Query Modifiers in MongoDB
Query modifiers in MongoDB are essential tools that adjust the behavior of queries to achieve various objectives such as shaping results, enhancing performance and efficiently retrieving documents from the database. These operators allow developers to manipulate query results for tasks like sorting,
7 min read
How to Connect MongoDB with Spring Boot?
In recent times MongoDB has been the most used database in the software industry. It's easy to use and learn This database stands on top of document databases it provides the scalability and flexibility that you want with the querying and indexing that you need. In this, we will explain how we conne
5 min read