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 return only value of a field in MongoDB?
To return only the values of a field in MongoDB, you can use projection with find() to select specific fields, or use forEach with an array to extract field values into a simple array format.
Syntax
// Method 1: Using projection
db.collection.find({}, { "fieldName": 1, "_id": 0 });
// Method 2: Using forEach to extract values
var output = [];
db.collection.find().forEach(function(doc) {
output.push(doc.fieldName);
});
Sample Data
db.returnOnlyValueOfFieldDemo.insertMany([
{ "ClientName": "Larry" },
{ "ClientName": "Chris" },
{ "ClientName": "Robert" },
{ "ClientName": "Ramit" }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c9ea537d628fa4220163b6e"),
ObjectId("5c9ea53bd628fa4220163b6f"),
ObjectId("5c9ea541d628fa4220163b70"),
ObjectId("5c9ea549d628fa4220163b71")
]
}
Method 1: Using Projection (Recommended)
Return only the ClientName field values without the _id ?
db.returnOnlyValueOfFieldDemo.find({}, { "ClientName": 1, "_id": 0 });
{ "ClientName": "Larry" }
{ "ClientName": "Chris" }
{ "ClientName": "Robert" }
{ "ClientName": "Ramit" }
Method 2: Using forEach to Extract Values
Extract field values into a simple array using forEach ?
var output = [];
db.returnOnlyValueOfFieldDemo.find().forEach(function(document) {
output.push(document.ClientName);
});
output;
[ "Larry", "Chris", "Robert", "Ramit" ]
Key Differences
| Method | Output Format | Use Case |
|---|---|---|
| Projection | Documents with selected fields | Display specific fields in query results |
| forEach | Simple array of values | Extract values for processing or analysis |
Conclusion
Use projection with find() to return documents with only specific fields, or use forEach to extract field values into a simple array format. Projection is more efficient for displaying results, while forEach is useful for data processing.
Advertisements
