String Sort by Custom sort in MongoDB?
{
"_id" : "1",
"name" : "Kathir",
"age" : "28",
"priority" : null
},
{
"_id" : "12",
"name" : "Raja",
"age" : "32",
"priority" : "high"
},
{
"_id" : "34",
"name" : "Sarath",
"age" : "24",
"priority" : "medium"
},
{
"_id" : "08",
"name" : "Chandru",
"age" : "24",
"priority" : "low"
},
how to sort this data in mongo sorting by priority as [“high”, “medium”, “low”, null] - i need this order,
please help me friends !..
Hi @Kathiresan_S ,
You can use a switch case statement to have sortable values based on your logic:
db.collection.aggregate([{
$addFields: {
sortPriority: {
$switch: {
branches: [
{
'case': {
$eq: [
'$priority',
'high'
]
},
then: 3
},
{
'case': {
$eq: [
'$priority',
'medium'
]
},
then: 2
},
{
'case': {
$eq: [
'$priority',
'low'
]
},
then: 1
}
],
'default': 0
}
}
}
}, {
$sort: {
sortPriority: -1
}
}])
This will sort as the result would be:
{ _id: '12',
name: 'Raja',
age: '32',
priority: 'high',
sortPriority: 3 }
{ _id: '34',
name: 'Sarath',
age: '24',
priority: 'medium',
sortPriority: 2 }
{ _id: '08',
name: 'Chandru',
age: '24',
priority: 'low',
sortPriority: 1 }
{ _id: '1',
name: 'Kathir',
age: '28',
priority: null,
sortPriority: 0 }
Thanks
Pavel
1 Like