One of my collections is a list of operations (or tasks) with some status. For example, a list of documents can look like this
{
_id: \'57befe57fc956d2e325
Based on what @chirdam said here is what the implementation looks like. Also the new sorted field is not present in the result as requested.
DataSet :
{
_id: '57befe57fc956d2e3252890c',
task: 'Go buy milk',
status: 'pending'
},
{
_id: '57befe5efc956d2e3252890d',
task: 'Cook dinner',
status: 'complete'
},
{
_id: '57befe5efc956d2e3252890e',
task: 'Play games',
status: 'new'
}
Query :
db.task.aggregate([
{ "$project" : {
"_id" : 1,
"task" : 1,
"status" : 1,
"order" : {
"$cond" : {
if : { "$eq" : ["$status", "new"] }, then : 1,
else : { "$cond" : {
"if" : { "$eq" : ["$status", "pending"] }, then : 2,
else : 3
}
}
}
}
} },
{"$sort" : {"order" : 1} },
{ "$project" : { "_id" : 1, "task" : 1, "status" : 1 } }
])
Output:
{ "_id" : "57befe5efc956d2e3252890e", "task" : "Play games", "status" : "new" }
{ "_id" : "57befe57fc956d2e3252890c", "task" : "Go buy milk", "status" : "pending" }
{ "_id" : "57befe5efc956d2e3252890d", "task" : "Cook dinner", "status" : "complete" }