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
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
_idfield 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.
Advertisements
