How to project grouping into object in MongoDB and display only the marks field?


Let us first create a document −

> var document= [
...    { "SubjectName" : "MySQL", "Marks" : 78 },
...    { "SubjectName" : "MongoDB", "Marks" : 89 },
...    { "SubjectName" : "Java", "Marks" : 71 },
... ];

Following is the query to display document −

> printjson(document);

This will produce the following output −

[
   {
      "SubjectName" : "MySQL",
      "Marks" : 78
   },
   {
      "SubjectName" : "MongoDB",
      "Marks" : 89
   },
   {
      "SubjectName" : "Java",
      "Marks" : 71
   }
]

Following is the query to project grouping into an object in MongoDB −

> var makeObject= {};
> document.forEach(function (d){
...    makeObject[d.SubjectName] = d.Marks;
... });
> printjson(makeObject);

This will produce the following output −

{ "MySQL" : 78, "MongoDB" : 89, "Java" : 71 }

Updated on: 15-May-2020

61 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements