Aggregations should allow an empty sort stage instead of returning an error
When you run an aggregation pipeline that contains an empty sort stage (like {"$sort": {}}
) MongoDB returns the error message "$sort stage must have at least one sort key". It would be really helpful if such a stage would work and simply not apply any sorting at all.
For one this would be more consistent with a find operation (e.g. db.runCommand({"find": "test", "sort": {}})
or db.test.find({}, {}, {"sort": {}})
) which does not return an error but simply does not sort the results. More importantly it would also make it easier for developers and frameworks to dynamically generate the aggregation stages.
For example: If you already have a JSON object that contains the fields to sort by and their sort order, you could simply put this object into a sort stage and add it to the pipeline. Currently you first have to make sure that the object is not the empty object and only then add the sort stage to the pipeline.
Another example: In Spring Data MongoDB you can explicitly state that you don't want any sorting. When you use this Sort.unsorted()
in a sort aggregation stage, it will generate the empty sort stage mentioned above ({"$sort": {}}
). This currently leads to an error. I have reported this error here (https://github.com/spring-projects/spring-data-mongodb/issues/4703) but for them it is also very cumbersome to modify their aggregation pipeline generation only to filter out an empty sort stage.
Hence it would be much better to solve this issue in MongoDB itself.