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] = value syntax.
  • 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.

Updated on: 2026-03-15T03:45:13+05:30

155 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements