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
Can I retrieve multiple documents from MongoDB by id?
Yes, you can retrieve multiple documents from MongoDB by id using the $in operator. This operator allows you to specify multiple values and returns documents where the field matches any of those values.
Syntax
db.collection.find({
_id: { $in: [id1, id2, id3, ...] }
});
Sample Data
Let us create a collection with sample documents ?
db.retrieveMultipleDocsByIdDemo.insertMany([
{ "_id": 10, "CustomerName": "John" },
{ "_id": 14, "CustomerName": "Chris" },
{ "_id": 20, "CustomerName": "Robert" },
{ "_id": 25, "CustomerName": "Sam" },
{ "_id": 30, "CustomerName": "Bob" },
{ "_id": 34, "CustomerName": "Carol" }
]);
{
"acknowledged": true,
"insertedIds": [10, 14, 20, 25, 30, 34]
}
View All Documents
db.retrieveMultipleDocsByIdDemo.find().pretty();
{ "_id": 10, "CustomerName": "John" }
{ "_id": 14, "CustomerName": "Chris" }
{ "_id": 20, "CustomerName": "Robert" }
{ "_id": 25, "CustomerName": "Sam" }
{ "_id": 30, "CustomerName": "Bob" }
{ "_id": 34, "CustomerName": "Carol" }
Example: Retrieve Multiple Documents by ID
To retrieve documents with IDs 10, 20, and 30 ?
db.retrieveMultipleDocsByIdDemo.find({
_id: { $in: [10, 20, 30] }
});
{ "_id": 10, "CustomerName": "John" }
{ "_id": 20, "CustomerName": "Robert" }
{ "_id": 30, "CustomerName": "Bob" }
Key Points
- The
$inoperator works with any field, not just_id - It returns documents in the order they exist in the collection, not the order specified in the array
- Non-existent IDs are silently ignored
Conclusion
Use the $in operator to efficiently retrieve multiple documents by their IDs in a single query. This approach is much faster than executing multiple individual find() operations.
Advertisements
