How to sort a field with custom order?

I have sample data like this:

        "title": "Complete Project Proposal",
        "priority": "very_important",
        "detail": "Finish writing and editing the project proposal document.",
        "due_date": "2024-04-15T00:00:00Z"
        "title": "Prepare Presentation Slides",
        "priority": "important",
        "detail": "Create slides for the upcoming team presentation.",
        "due_date": "2024-04-10T18:00:00Z"
        "title": "Send Monthly Report",
        "priority": "important",
        "detail": "Compile data and send the monthly report to stakeholders.",
        "due_date": "2024-04-20T12:00:00Z"
        "title": "Review Code Changes",
        "priority": "not_important",
        "detail": "Review and provide feedback on recent code changes.",
        "due_date": "2024-04-12T09:00:00Z"

and I have this pipeline:

    "$match": {
      "due_date": {
        "$gt": "2024-04-04T09:49:09.952Z"
    "$sort": {
      [sort]: sortOrder,// here `sort` can be replaced with either due_date or priority
      "_id": 1

There are 3 priorities: very_important, important, and not_important. I want to sort based on priority with this order, for ascending not_important->important->very_important, for descending very_important->important->not_important. So, the question is how can I perform that custom sort?


Kindly refer to these resolved cases. It may help.

case 1 : using $switch
case 2: using if else block within $cond
case 3: using nested $cond

Case 1:

Case 2:

Case 3:


1 Like