Sort mongo results by enum string value

Is there a way to sort documents from MongoDB based on enumerating string values?

What I'm trying to achieve is just sorting the log message objects based on severity. So the docs look like this:

{message: 'An error', severity: 'error'}
{message: 'A warning', severity: 'warning'}
{message: 'Informational message', severity: 'info'}

      

And I would like the results to be sorted by logical severity (e.g. error-> warning-> info) rather than alphabetically.

+3


source to share


1 answer


I know this is not what you want, but you can use a code based system:

{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.

+7


source







All Articles