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
MongoDB query select and display only a specific field from the document?
To select and display only specific fields from MongoDB documents, use the projection parameter in the find() method. Set the desired field to 1 (or true) to include it, and use _id: 0 to exclude the default ObjectId field.
Syntax
db.collection.find(
{},
{ fieldName: 1, _id: 0 }
);
Sample Data
Let us create a collection with sample documents ?
db.querySelectDemo.insertMany([
{ UserId: 100, UserName: "Chris", UserAge: 25 },
{ UserId: 101, UserName: "Robert", UserAge: 26 },
{ UserId: 103, UserName: "David", UserAge: 27 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5ce90eb478f00858fb12e90e"),
ObjectId("5ce90ec578f00858fb12e90f"),
ObjectId("5ce90ed478f00858fb12e910")
]
}
Display all documents to verify the data ?
db.querySelectDemo.find();
{
"_id": ObjectId("5ce90eb478f00858fb12e90e"),
"UserId": 100,
"UserName": "Chris",
"UserAge": 25
}
{
"_id": ObjectId("5ce90ec578f00858fb12e90f"),
"UserId": 101,
"UserName": "Robert",
"UserAge": 26
}
{
"_id": ObjectId("5ce90ed478f00858fb12e910"),
"UserId": 103,
"UserName": "David",
"UserAge": 27
}
Example: Select Only UserName Field
To display only the UserName field from all documents ?
db.querySelectDemo.find({}, { _id: 0, UserName: 1 });
{ "UserName": "Chris" }
{ "UserName": "Robert" }
{ "UserName": "David" }
Key Points
- Use
1ortrueto include specific fields in the projection. - Set
_id: 0to exclude the default ObjectId field from results. - The first parameter
{}represents the query filter (empty means match all documents). - The second parameter defines which fields to include or exclude in the output.
Conclusion
MongoDB's projection feature in find() allows you to retrieve only specific fields from documents, reducing network overhead and improving query performance. Use { fieldName: 1, _id: 0 } to select specific fields while excluding the ObjectId.
Advertisements
