Get the array of _id in MongoDB?

In MongoDB, the _id field is a mandatory field that acts as the primary key for each document. To retrieve documents by matching their _id values against an array of specific values, use the $in operator.

Syntax

db.collectionName.find({ _id: { $in: [value1, value2, value3, ...] } });

Create Sample Data

db.selectInWhereIdDemo.insertMany([
    {"_id": 23},
    {"_id": 28},
    {"_id": 45},
    {"_id": 75},
    {"_id": 85},
    {"_id": 145}
]);
{
    "acknowledged": true,
    "insertedIds": [23, 28, 45, 75, 85, 145]
}

Display All Documents

db.selectInWhereIdDemo.find();
{ "_id": 23 }
{ "_id": 28 }
{ "_id": 45 }
{ "_id": 75 }
{ "_id": 85 }
{ "_id": 145 }

Example: Get Documents with Specific _id Values

Retrieve documents where _id matches any value in the array [23, 45, 85, 145] ?

db.selectInWhereIdDemo.find({ _id: { $in: [23, 45, 85, 145] } });
{ "_id": 23 }
{ "_id": 45 }
{ "_id": 85 }
{ "_id": 145 }

Key Points

  • The $in operator matches documents where the field value equals any value in the specified array.
  • Works with any data type for _id values (ObjectId, numbers, strings).
  • Returns documents in the order they appear in the collection, not the array order.

Conclusion

Use the $in operator with an array of _id values to efficiently retrieve multiple documents by their primary keys. This method is ideal for batch document retrieval operations.

Updated on: 2026-03-15T00:23:26+05:30

826 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements