2

I have a collection called INFODOCS which has a field called ML_PRIORITY(HIGH/MEDIUM/LOW) and STATUS(True/False/Null). I want to determine count of STATUS for each ML_PRIORITY and then sort the ML_PRIORITY in order High, Medium and Low.

[
  {
    "_id": "1",
    "ML_PRIORITY" : "HIGH",
    "STATUS" : "True"
  },
  {
    "_id": "2",
    "ML_PRIORITY" : "HIGH",
    "STATUS" : ""
  },
  {
    "_id": "3",
    "ML_PRIORITY" : "HIGH",
    "STATUS" : "False"
  },
  {
    "_id": "4",
    "ML_PRIORITY" : "MEDIUM",
    "STATUS" : ""
  },
  {
    "_id": "5",
    "ML_PRIORITY" : "Low",
    "STATUS" : ""
  }
]

I was able to determine the count of STATUS for each ML_PRIORITY using below aggregation pipeline but I am not sure how can I custom sort the ML_PRIORITY as $sort has only two option (1 and -1)

db.collection.aggregate([
    {
        '$group': {
            '_id': '$ML_PRIORITY', 
            'QUALITYCHECKDONE': {
                '$sum': {
                    '$cond': [
                        {
                            '$eq': [
                                '$STATUS', 'TRUE'
                            ]
                        }, 1, 0
                    ]
                }
            }, 
            'QUALITYCHECKNOTDONE': {
                '$sum': {
                    '$cond': [
                        {
                            '$eq': [
                                '$STATUS', ''
                            ]
                        }, 1, 0
                    ]
                }
            }, 
            'QUALITYCHECKNOTREQ': {
                '$sum': {
                    '$cond': [
                        {
                            '$eq': [
                                '$STATUS', 'FALSE'
                            ]
                        }, 1, 0
                    ]
                }
            }
        }
    }, {
        '$project': {
            '_id': 0, 
            'ML_PRIORITY': '$_id', 
            'QUALITYCHECKDONE': 1, 
            'QUALITYCHECKNOTDONE': 1, 
            'QUALITYCHECKNOTREQ': 1
        }
    }
])

Example - https://mongoplayground.net/p/anAwoqZk2Ys

1 Answer 1

1

One option is to replace your last step with 3 steps, in order to $set an order field, $sort, and $unset it:

[
 {$set: {
      order: {$indexOfArray: [["HIGH", "MEDIUM", "Low"], "$_id"]},
      "ML_PRIORITY": "$_id"
  }},
  {$sort: {order: 1}},
  {$unset: ["_id", "order"]}
]

See how it works on the playground example

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.