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 $in operator 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.

Updated on: 2026-03-15T00:36:46+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements