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
Display only a single field from all the documents in a MongoDB collection
To display only a single field from all documents in a MongoDB collection, use projection in the find() method. Set the desired field to 1 to include it, or set unwanted fields to 0 to exclude them.
Syntax
db.collection.find({}, {fieldName: 1, _id: 0});
// OR
db.collection.find({}, {unwantedField1: 0, unwantedField2: 0});
Sample Data
db.demo384.insertMany([
{"StudentName": "Chris Brown", "StudentCountryName": "US"},
{"StudentName": "David Miller", "StudentCountryName": "AUS"},
{"StudentName": "John Doe", "StudentCountryName": "UK"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e5b67a022064be7ab44e7f2"),
ObjectId("5e5b67ab22064be7ab44e7f3"),
ObjectId("5e5b67b422064be7ab44e7f4")
]
}
Display all documents to see the complete structure ?
db.demo384.find();
{ "_id": ObjectId("5e5b67a022064be7ab44e7f2"), "StudentName": "Chris Brown", "StudentCountryName": "US" }
{ "_id": ObjectId("5e5b67ab22064be7ab44e7f3"), "StudentName": "David Miller", "StudentCountryName": "AUS" }
{ "_id": ObjectId("5e5b67b422064be7ab44e7f4"), "StudentName": "John Doe", "StudentCountryName": "UK" }
Method 1: Include Only Desired Field
Display only StudentName by setting it to 1 and excluding _id ?
db.demo384.find({}, {StudentName: 1, _id: 0});
{ "StudentName": "Chris Brown" }
{ "StudentName": "David Miller" }
{ "StudentName": "John Doe" }
Method 2: Exclude Unwanted Fields
Display only StudentCountryName by excluding other fields ?
db.demo384.find({}, {_id: 0, StudentName: 0});
{ "StudentCountryName": "US" }
{ "StudentCountryName": "AUS" }
{ "StudentCountryName": "UK" }
Key Points
- Use
fieldName: 1to include specific fields (inclusion projection) - Use
fieldName: 0to exclude specific fields (exclusion projection) - Always exclude
_idwith_id: 0unless you need it - Cannot mix inclusion and exclusion (except for
_id)
Conclusion
MongoDB projection allows you to control which fields appear in query results. Use {fieldName: 1, _id: 0} for inclusion or {unwantedField: 0} for exclusion to display only the required single field.
Advertisements
