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
Return a specific field in MongoDB?
To return a specific field in MongoDB, use the projection parameter in the find() method. Set the desired field to 1 to include it and _id to 0 to exclude the default ID field.
Syntax
db.collection.find({}, {fieldName: 1, _id: 0});
Sample Data
db.specificFieldDemo.insertMany([
{"FirstName": "John", "LastName": "Doe"},
{"FirstName": "John", "LastName": "Smith"},
{"FirstName": "David", "LastName": "Miller"},
{"FirstName": "Sam", "LastName": "Williams"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cb8019a623186894665ae31"),
ObjectId("5cb801ab623186894665ae32"),
ObjectId("5cb801b3623186894665ae33"),
ObjectId("5cb801bf623186894665ae34")
]
}
Example 1: Display All Documents
db.specificFieldDemo.find().pretty();
{
"_id": ObjectId("5cb8019a623186894665ae31"),
"FirstName": "John",
"LastName": "Doe"
}
{
"_id": ObjectId("5cb801ab623186894665ae32"),
"FirstName": "John",
"LastName": "Smith"
}
{
"_id": ObjectId("5cb801b3623186894665ae33"),
"FirstName": "David",
"LastName": "Miller"
}
{
"_id": ObjectId("5cb801bf623186894665ae34"),
"FirstName": "Sam",
"LastName": "Williams"
}
Example 2: Return Only LastName Field
db.specificFieldDemo.find({}, {_id: 0, LastName: 1});
{"LastName": "Doe"}
{"LastName": "Smith"}
{"LastName": "Miller"}
{"LastName": "Williams"}
Key Points
- Use
1to include a field and0to exclude it in the projection parameter. - The
_idfield is included by default ? set_id: 0to exclude it. - You can return multiple specific fields by setting each to
1.
Conclusion
MongoDB's projection parameter in find() allows selective field retrieval. Use {fieldName: 1, _id: 0} to return only the desired field without the default ID.
Advertisements
