Fetch all the ids of MongoDB documents?

To fetch all the document IDs from a MongoDB collection, use the find() method with projection to return only the _id field by excluding other fields.

Syntax

db.collection.find({}, {"fieldName": 0});
// OR
db.collection.find({}, {"_id": 1});

Sample Data

Let us create a collection with sample documents ?

db.demo169.insertMany([
    {"StudentName": "Chris"},
    {"StudentName": "Bob"},
    {"StudentName": "David"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e36975e9e4f06af551997d7"),
        ObjectId("5e3697629e4f06af551997d8"),
        ObjectId("5e3697679e4f06af551997d9")
    ]
}

Method 1: Exclude Other Fields (Recommended)

Use projection to exclude all fields except _id ?

db.demo169.find({}, {"StudentName": 0});
{ "_id": ObjectId("5e36975e9e4f06af551997d7") }
{ "_id": ObjectId("5e3697629e4f06af551997d8") }
{ "_id": ObjectId("5e3697679e4f06af551997d9") }

Method 2: Explicitly Include Only _id

db.demo169.find({}, {"_id": 1});
{ "_id": ObjectId("5e36975e9e4f06af551997d7") }
{ "_id": ObjectId("5e3697629e4f06af551997d8") }
{ "_id": ObjectId("5e3697679e4f06af551997d9") }

Key Points

  • The _id field is included by default unless explicitly excluded with {"_id": 0}.
  • Method 1 is more efficient when you have many fields to exclude.
  • Both methods return identical results containing only document IDs.

Conclusion

Use find() with projection to fetch only document IDs by excluding other fields. This approach is memory-efficient and returns clean results containing just the _id values.

Updated on: 2026-03-15T02:25:31+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements