Is there any way to sort documents from MongoDB based on an enumeration of string values?
What I'm trying to achieve is simply sorting log message objects based on a severity. So the documents look like:
{message: 'An error', severity: 'error'}
{message: 'A warning', severity: 'warning'}
{message: 'Informational message', severity: 'info'}
And I'd like the results sorted by the logical severity (e.g. error->warning->info) rather than alphabetical.
This, however, made the easiest approach impossible, which was to sort the data within the application. It was necessary to involve MongoDB in the process of sorting, but since MongoDB doesn’t have any schema, I had to pass the order of enum values in some other way.
If the sort keys correspond to the index keys or an index prefix , MongoDB can use the index to sort the query results. A prefix of a compound index is a subset that consists of one or more keys at the start of the index key pattern. For example, create a compound index on the data collection:
These building blocks are fields to be sorted and the sort order. The sorting order in MongoDB is defined by either a one (1) or a minus (-1). Here the positive one represents the ascending order, while the negative one represents the descending order.
In this example, I use the “make” text field to obtain the results in ascending order. The operator one ( {“make”:1}) is used to indicate the ascending order, and MongoDB projection is used to filter out all the other fields except the “make” field.
I know this not what you want but you can use code-value based system on that:
{message: 'An error', code : 0, severity: 'error'}
{message: 'A warning', code : 1, severity: 'warning'}
{message: 'Informational message', code : 2, severity: 'info'}
then sort by code.
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