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
Selecting only a single field from MongoDB?
To select only a single field from MongoDB, use the projection parameter in the find() method. Set the desired field to 1 to include it, and set _id to 0 to exclude the default ID field.
Syntax
db.collection.find(
{ query },
{ fieldName: 1, _id: 0 }
);
Sample Data
db.selectingASingleFieldDemo.insertMany([
{"StudentFirstName": "John", "StudentAge": 23, "StudentCountryName": "US"},
{"StudentFirstName": "Carol", "StudentAge": 21, "StudentCountryName": "UK"},
{"StudentFirstName": "David", "StudentAge": 24, "StudentCountryName": "AUS"},
{"StudentFirstName": "Robert", "StudentAge": 26, "StudentCountryName": "AUS"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cd547142cba06f46efe9f02"),
ObjectId("5cd5471f2cba06f46efe9f03"),
ObjectId("5cd5472c2cba06f46efe9f04"),
ObjectId("5cd548382cba06f46efe9f05")
]
}
Example 1: Select Single Field Without Conditions
Select only the StudentFirstName field from all documents ?
db.selectingASingleFieldDemo.find(
{},
{ StudentFirstName: 1, _id: 0 }
);
{ "StudentFirstName": "John" }
{ "StudentFirstName": "Carol" }
{ "StudentFirstName": "David" }
{ "StudentFirstName": "Robert" }
Example 2: Select Single Field with Query Conditions
Select only StudentFirstName for students older than 21 from Australia ?
db.selectingASingleFieldDemo.find(
{
$and: [
{ StudentAge: { $gt: 21 } },
{ "StudentCountryName": "AUS" }
]
},
{ StudentFirstName: 1, _id: 0 }
);
{ "StudentFirstName": "David" }
{ "StudentFirstName": "Robert" }
Key Points
- Set field to
1to include it in results. - Set
_id: 0to exclude the default ID field. - Combine projection with query conditions for filtered single-field results.
Conclusion
Use projection in MongoDB's find() method to select only specific fields. Set desired fields to 1 and _id to 0 for clean single-field output.
Advertisements
