MongoDB sort with a custom expression or function

前端 未结 1 435
礼貌的吻别
礼貌的吻别 2020-12-16 14:27

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         


        
相关标签:
1条回答
  • 2020-12-16 15:18

    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" }
    
    0 讨论(0)
提交回复
热议问题