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
How to select a single field in MongoDB?
You can select a single field in MongoDB using the projection parameter in the find() method. Projection lets you specify which fields to include or exclude in the query results. The syntax is −
db.yourCollectionName.find(
{"yourFieldName": yourValue},
{"yourSingleFieldName": 1, _id: 0}
);
In the above syntax, "yourSingleFieldName": 1 means include this field in the result, and _id: 0 means exclude the _id field which MongoDB includes by default.
Creating a Sample Collection
To understand the above syntax, let us create a collection with documents ?
db.singleFieldDemo.insertOne({"StudentName": "David", "StudentAge": 28});
db.singleFieldDemo.insertOne({"StudentName": "Bob", "StudentAge": 18});
db.singleFieldDemo.insertOne({"StudentName": "Chris", "StudentAge": 24});
db.singleFieldDemo.insertOne({"StudentName": "Robert", "StudentAge": 26});
Now display all documents from the collection using the find() method −
db.singleFieldDemo.find().pretty();
The following is the output −
{
"_id" : ObjectId("5c6eba356fd07954a489067c"),
"StudentName" : "David",
"StudentAge" : 28
}
{
"_id" : ObjectId("5c6eba406fd07954a489067d"),
"StudentName" : "Bob",
"StudentAge" : 18
}
{
"_id" : ObjectId("5c6eba4c6fd07954a489067e"),
"StudentName" : "Chris",
"StudentAge" : 24
}
{
"_id" : ObjectId("5c6eba586fd07954a489067f"),
"StudentName" : "Robert",
"StudentAge" : 26
}
Selecting a Single Field
Here is the query to select only the StudentName field for the student whose age is 18 −
db.singleFieldDemo.find(
{"StudentAge": 18},
{"StudentName": 1, "_id": 0}
);
The following is the output −
{ "StudentName" : "Bob" }
Only the StudentName field is returned. The _id field is excluded because we set _id: 0, and StudentAge is excluded because we did not set it to 1 in the projection.
Selecting a Single Field for All Documents
To retrieve a single field from all documents (without filtering), pass an empty query object as the first parameter ?
db.singleFieldDemo.find(
{},
{"StudentName": 1, "_id": 0}
);
The following is the output −
{ "StudentName" : "David" }
{ "StudentName" : "Bob" }
{ "StudentName" : "Chris" }
{ "StudentName" : "Robert" }
Conclusion
Use the projection parameter in MongoDB's find() method to select a single field. Set the desired field to 1 to include it and _id to 0 to exclude the default ID field from the results.
