Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDb aggregate: Select all group by x

I am trying to convert the following SQL-like statement into a mongo-query, using the new aggregation framework.

SELECT * FROM ...
GROUP BY class

So far I have managed to write the following, which works well - yet only a single field is selected / returned.

db.studentMarks.aggregate(
   {
     $project: {
        class : 1 // Inclusion mode
     }
   },
   {
     $group: {
        _id: "$class"
     }
   }
);

I have also attempted play with the $project pipelines exclusion mode, by adding a field name which never exists, in order to trick MongoDb to return all the fields. While the syntax is correct, no results are returned. E.g:

db.studentMarks.aggregate(
   {
     $project: {
        noneExistingField : 0 // Exclusion mode...
                              // Attempt to trick mongo into returning all fields
                              // sadly this fails - empty array is returned.
     }
   },
   {
     $group: {
        _id: "$class"
     }
   }
);

The reason why I need all fields to be returned, is that I will not know (in the future) what fields are going to be present or not. E.g. a "student" might have field x, y, z or not. Thus, I need to "select all", group the results by a single field and return it, for a generic purpose - doesn't have to be for "student marks", can be for any type of dataset, without knowing all the fields.

For the mentioned reason, I cannot simply project all the fields which must be returned - once again - because I will not know all the fields.

I hope that someone knows a good way of solving my problem, using the new aggregation framework.

like image 669
user1406347 Avatar asked Nov 14 '22 05:11

user1406347


1 Answers

Simply don't use the project operator in the pipeline.

db.studentMarks.aggregate({
  $group: { _id: "$class" }
});
like image 148
Tyler Brock Avatar answered Jan 22 '23 00:01

Tyler Brock