Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort mongo results by string enum value

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.

like image 361
Eric Nicholson Avatar asked Dec 18 '14 19:12

Eric Nicholson


People also ask

Is it possible to sort enum values in MongoDB?

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.

How to use index to sort query results in MongoDB?

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:

What are the building blocks of sorting in MongoDB?

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.

How do I get the ascending order of results in MongoDB?

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.


1 Answers

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.

like image 64
2 revs, 2 users 67% Avatar answered Sep 27 '22 19:09

2 revs, 2 users 67%