Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
In MongoDB, is using $in search faster than multiple single searches?
Yes, using $in is significantly faster than multiple single searches. The $in operator performs a single database query to match multiple values, while multiple single searches require separate round trips to the database, increasing network overhead and execution time.
Syntax
db.collection.find({
field: { $in: [value1, value2, value3] }
});
Sample Data
db.demo653.insertMany([
{ subject: "MySQL" },
{ subject: "MongoDB" },
{ subject: "Java" },
{ subject: "C" },
{ subject: "C++" }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5ea04b274deddd72997713c0"),
ObjectId("5ea04b304deddd72997713c1"),
ObjectId("5ea04b354deddd72997713c2"),
ObjectId("5ea04b384deddd72997713c3"),
ObjectId("5ea04b3b4deddd72997713c4")
]
}
Method 1: Using $in (Recommended)
Search for multiple subjects in a single query ?
db.demo653.find({
subject: { $in: ["MySQL", "C++", "C"] }
});
{ "_id": ObjectId("5ea04b274deddd72997713c0"), "subject": "MySQL" }
{ "_id": ObjectId("5ea04b384deddd72997713c3"), "subject": "C" }
{ "_id": ObjectId("5ea04b3b4deddd72997713c4"), "subject": "C++" }
Method 2: Multiple Single Searches (Inefficient)
The inefficient approach requires three separate queries ?
db.demo653.find({ subject: "MySQL" });
db.demo653.find({ subject: "C++" });
db.demo653.find({ subject: "C" });
Performance Comparison
| Method | Database Queries | Network Round Trips | Performance |
|---|---|---|---|
| $in operator | 1 | 1 | Fast |
| Multiple single searches | 3 | 3 | Slower |
Key Points
-
$inreduces network latency by combining multiple searches into one query. - Database optimization is better with single queries handling multiple conditions.
- Index usage is more efficient with
$inoperations.
Conclusion
The $in operator is always faster than multiple single searches because it minimizes database round trips and leverages MongoDB's internal optimization. Use $in when searching for multiple values in the same field.
Advertisements
