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 project grouping into object in MongoDB and display only the marks field?
To project grouping into an object in MongoDB and display only the marks field, you can use JavaScript methods to transform array data into key-value objects. This approach converts subject-marks pairs into a single object where subject names become keys and marks become values.
Syntax
var resultObject = {};
arrayData.forEach(function(item) {
resultObject[item.keyField] = item.valueField;
});
Sample Data
var document = [
{ "SubjectName": "MySQL", "Marks": 78 },
{ "SubjectName": "MongoDB", "Marks": 89 },
{ "SubjectName": "Java", "Marks": 71 }
];
Display Original Array
printjson(document);
[
{
"SubjectName": "MySQL",
"Marks": 78
},
{
"SubjectName": "MongoDB",
"Marks": 89
},
{
"SubjectName": "Java",
"Marks": 71
}
]
Project Grouping into Object
Transform the array into an object where subject names become keys and marks become values ?
var makeObject = {};
document.forEach(function(d) {
makeObject[d.SubjectName] = d.Marks;
});
printjson(makeObject);
{ "MySQL": 78, "MongoDB": 89, "Java": 71 }
Key Points
-
forEach()iterates through each array element to build the object structure. - Dynamic property assignment uses
object[key] = valuesyntax. - The result is a flat object with subject names as keys and marks as values.
Conclusion
Use JavaScript forEach() method to transform MongoDB array data into key-value objects. This technique effectively groups data by converting array elements into object properties for easier data manipulation.
Advertisements
