MongoDB使用自定义表达式或函数排序

Yan*_*hon 13 mongodb

我的一个集合是具有某种状态的操作(或任务)列表.例如,文档列表可能如下所示

{
  _id: '57befe57fc956d2e3252890c',
  task: 'Go buy milk',
  status: 'pending'
},
{
  _id: '57befe5efc956d2e3252890d',
  task: 'Cook dinner',
  status: 'complete'
},
{
  _id: '57befe5efc956d2e3252890e',
  task: 'Play games',
  status: 'new'
}
Run Code Online (Sandbox Code Playgroud)

我想根据它们的状态对这个列表进行排序new > pending > complete.

如何在不创建额外字段的情况下使用MongoDB?我问,在我的情况下,排序顺序可能是预配置的(pending > new > complete例如,用户可能有他们的偏好)

use*_*887 7

基于@chirdam所说的这是实现的样子.此外,新的排序字段不会按要求出现在结果中.

数据集:

{
  _id: '57befe57fc956d2e3252890c',
  task: 'Go buy milk',
  status: 'pending'
},
{
  _id: '57befe5efc956d2e3252890d',
  task: 'Cook dinner',
  status: 'complete'
},
{
  _id: '57befe5efc956d2e3252890e',
  task: 'Play games',
  status: 'new'
}
Run Code Online (Sandbox Code Playgroud)

查询:

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 } }
])
Run Code Online (Sandbox Code Playgroud)

输出:

{ "_id" : "57befe5efc956d2e3252890e", "task" : "Play games", "status" : "new" }
{ "_id" : "57befe57fc956d2e3252890c", "task" : "Go buy milk", "status" : "pending" }
{ "_id" : "57befe5efc956d2e3252890d", "task" : "Cook dinner", "status" : "complete" }
Run Code Online (Sandbox Code Playgroud)

  • 您可以将所需的顺序放入数组中,并使用"$ indexOfArray"表达式生成排序字段,而不是多个if-then-else序列.这里有一个例子:http://www.kamsky.org/stupid-tricks-with-mongodb/using-34-aggregation-to-return-documents-in-same-order-as-in-expression (4认同)
  • @AsyaKamsky 你应该添加它作为答案。我相信人们会错过你的评论,这是一个非常好的解决方案。 (2认同)