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.
Simply don't use the project operator in the pipeline.
db.studentMarks.aggregate({
$group: { _id: "$class" }
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With