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
How to retrieve a value from MongoDB by its key name?
To retrieve a value from MongoDB by its key name, use projection in the find() method to specify which fields to return while excluding others.
Syntax
db.collectionName.find({}, {"fieldName": 1});
Set the field value to 1 to include it, or 0 to exclude it from the result.
Sample Data
db.retrieveValueFromAKeyDemo.insertMany([
{"CustomerName": "Larry", "CustomerAge": 21, "CustomerCountryName": "US"},
{"CustomerName": "Chris", "CustomerAge": 24, "CustomerCountryName": "AUS"},
{"CustomerName": "Mike", "CustomerAge": 26, "CustomerCountryName": "UK"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c9163b5a56efcc0f9e69048"),
ObjectId("5c9163c4a56efcc0f9e69049"),
ObjectId("5c9163d3a56efcc0f9e6904a")
]
}
Example: Retrieve Specific Field
To retrieve only the CustomerCountryName field from all documents ?
db.retrieveValueFromAKeyDemo.find({}, {"CustomerCountryName": 1});
{
"_id": ObjectId("5c9163b5a56efcc0f9e69048"),
"CustomerCountryName": "US"
}
{
"_id": ObjectId("5c9163c4a56efcc0f9e69049"),
"CustomerCountryName": "AUS"
}
{
"_id": ObjectId("5c9163d3a56efcc0f9e6904a"),
"CustomerCountryName": "UK"
}
Exclude _id Field
To retrieve only the field value without the _id field ?
db.retrieveValueFromAKeyDemo.find({}, {"CustomerCountryName": 1, "_id": 0});
{
"CustomerCountryName": "US"
}
{
"CustomerCountryName": "AUS"
}
{
"CustomerCountryName": "UK"
}
Key Points
- Use
1to include fields and0to exclude fields in projection - The
_idfield is included by default unless explicitly excluded with"_id": 0 - You cannot mix inclusion and exclusion in the same projection (except for
_id)
Conclusion
Use projection in MongoDB's find() method to retrieve specific field values by their key names. Set field values to 1 for inclusion and 0 for exclusion to control which data is returned.
Advertisements
