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

MongoDBDatabaseBig Data Analytics

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 }
raja
Published on 15-May-2020 10:01:11
Advertisements