To understand correctly what you want, we would need more sample documents and the expected results.
If you stick with the original document structure, I think the first stage will be to extract the stage date that you want with a $set that uses $switch to get the date.
{ "$set" : {
"_tmp.deadline" : { "$switch" : {
"branches" : [
{
"case" : { "$eq" : [ "$status" , "pending" ] } ,
"then" : { "$stages.pending.deadline" }
} ,
{
"case" : { "$eq" : [ "$status" , "in work" ] } ,
"then" : { "$stages.in work.deadline" }
} ,
{
"case" : { "$eq" : [ "$status" , "done" ] } ,
"then" : { "$stages.done.deadline" }
}
]
} }
} }
Then another $set that convert the deadline into a value that can be sorted
{ "$set" : {
"_tmp.sortable_deadline" : { "$dateFromString" : {
"dateString" : "$_tmp.deadline" ,
"format" : "%d/%m/%Y"
} }
} }
The you would be able to sort
{ "$sort" : {
"_tmp.sortable_deadline" : 1
} }
A cleanup $project to remove all temporary fields
{ "$project" : { "_tmp" : 0 } }