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
Particular field as result in MongoDB?
To get particular fields as a result in MongoDB, use field projection with the find() or findOne() methods. This allows you to return only specific fields instead of entire documents.
Syntax
db.collection.findOne(
{ "fieldName": "value" },
{ "fieldToInclude": 1, "_id": 0 }
);
Sample Data
db.particularFieldDemo.insertMany([
{
"EmployeeName": "John Smith",
"EmployeeAge": 26,
"EmployeeTechnology": "MongoDB"
},
{
"EmployeeName": "Chris Brown",
"EmployeeAge": 28,
"EmployeeTechnology": "Java"
},
{
"EmployeeName": "David Miller",
"EmployeeAge": 30,
"EmployeeTechnology": "MySQL"
},
{
"EmployeeName": "John Doe",
"EmployeeAge": 31,
"EmployeeTechnology": "C++"
}
]);
Example 1: Find Specific Field Only
Retrieve only the EmployeeName for an employee with Java technology ?
db.particularFieldDemo.findOne(
{ "EmployeeTechnology": "Java" },
{ "EmployeeName": 1 }
);
{
"_id": ObjectId("5cd9b4d2b50a6c6dd317ada3"),
"EmployeeName": "Chris Brown"
}
Example 2: Exclude _id Field
Get only the name without the _id field ?
db.particularFieldDemo.findOne(
{ "EmployeeTechnology": "Java" },
{ "EmployeeName": 1, "_id": 0 }
);
{
"EmployeeName": "Chris Brown"
}
Example 3: Multiple Fields
Retrieve both name and age for a specific employee ?
db.particularFieldDemo.findOne(
{ "EmployeeTechnology": "MongoDB" },
{ "EmployeeName": 1, "EmployeeAge": 1, "_id": 0 }
);
{
"EmployeeName": "John Smith",
"EmployeeAge": 26
}
Key Points
- Use
1to include a field and0to exclude it - The
_idfield is included by default unless explicitly excluded with"_id": 0 - Both
find()andfindOne()support field projection
Conclusion
Field projection in MongoDB allows you to retrieve only the required fields, reducing network traffic and improving query performance. Use the second parameter in find() or findOne() to specify which fields to include or exclude.
Advertisements
