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
Projection of one column in MongoDB?
In MongoDB, projection allows you to display only specific fields from documents instead of returning all fields. To project a single column (field), use the find() method with a projection document that specifies which fields to include or exclude.
Syntax
db.collection.find({}, {fieldToShow: 1, _id: 0});
Or exclude unwanted fields:
db.collection.find({}, {fieldToHide: 0, anotherField: 0});
Sample Data
Let us first create a collection with documents −
db.demo216.insertMany([
{"ClientName": "John", "ClientAge": 34},
{"ClientName": "Bob", "ClientAge": 32},
{"ClientName": "Mike", "ClientAge": 35}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e3e351003d395bdc213470c"),
ObjectId("5e3e351703d395bdc213470d"),
ObjectId("5e3e351c03d395bdc213470e")
]
}
Display all documents from the collection −
db.demo216.find();
{ "_id": ObjectId("5e3e351003d395bdc213470c"), "ClientName": "John", "ClientAge": 34 }
{ "_id": ObjectId("5e3e351703d395bdc213470d"), "ClientName": "Bob", "ClientAge": 32 }
{ "_id": ObjectId("5e3e351c03d395bdc213470e"), "ClientName": "Mike", "ClientAge": 35 }
Method 1: Exclude Unwanted Fields
To project only the ClientName field, exclude the _id and ClientAge fields −
db.demo216.find({}, {_id: 0, "ClientAge": 0});
{ "ClientName": "John" }
{ "ClientName": "Bob" }
{ "ClientName": "Mike" }
Method 2: Include Only Desired Field
Alternatively, explicitly include only the ClientName field −
db.demo216.find({}, {"ClientName": 1, _id: 0});
{ "ClientName": "John" }
{ "ClientName": "Bob" }
{ "ClientName": "Mike" }
Key Points
- Use
1to include fields and0to exclude fields in projection - The
_idfield is included by default; explicitly set_id: 0to exclude it - Cannot mix inclusion and exclusion (except for
_id)
Conclusion
MongoDB projection enables selective field retrieval using find() with a projection document. Use 0 to exclude unwanted fields or 1 to include only desired fields for efficient single-column queries.
