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
Querying only the field name and display only the id in MongoDB?
To query only specific fields in MongoDB, use projection to control which fields appear in the result. Set field values to 1 to include or 0 to exclude them from the output.
Syntax
db.collection.find(query, projection);
// Include specific fields
db.collection.find({}, {fieldName: 1});
// Exclude specific fields
db.collection.find({}, {fieldName: 0});
Sample Data
db.demo650.insertMany([
{_id: 101, details: {Name: "Chris", Age: 21}},
{_id: 102, details: {Name: "Bob", Age: 22}},
{_id: 103, details: {Name: "Sam", Age: 20}},
{_id: 104, details: {Name: "Robert", Age: 24}}
]);
{
"acknowledged": true,
"insertedIds": {
"0": 101,
"1": 102,
"2": 103,
"3": 104
}
}
Display All Documents
db.demo650.find();
{ "_id": 101, "details": { "Name": "Chris", "Age": 21 } }
{ "_id": 102, "details": { "Name": "Bob", "Age": 22 } }
{ "_id": 103, "details": { "Name": "Sam", "Age": 20 } }
{ "_id": 104, "details": { "Name": "Robert", "Age": 24 } }
Example: Hide Details Field, Show Only _id
To exclude the details field and display only the _id, set details to 0 ?
db.demo650.find({}, {details: 0});
{ "_id": 101 }
{ "_id": 102 }
{ "_id": 103 }
{ "_id": 104 }
Key Points
- The
_idfield is included by default unless explicitly excluded with_id: 0. - Use
0to exclude fields and1to include specific fields. - You cannot mix inclusion and exclusion projections (except for
_id).
Conclusion
MongoDB projection allows you to control query output by including or excluding specific fields. Use 0 to hide unwanted fields while keeping the _id field visible by default.
Advertisements
