我的一个集合是具有某种状态的操作(或任务)列表.例如,文档列表可能如下所示
{
_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例如,用户可能有他们的偏好)
基于@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)
| 归档时间: |
|
| 查看次数: |
2655 次 |
| 最近记录: |