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

{
  _id: '57befe57fc956d2e3252890c',
  task: 'Go buy milk',
  status: 'pending'
},
{
  _id: '57befe5efc956d2e3252890d',
  task: 'Cook dinner',
  status: 'complete'
},
{
  _id: '57befe5efc956d2e3252890e',
  task: 'Play games',
  status: 'new'
}

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

我如何使用MongoDB而不必创建额外的字段?我的问题是,在我的情况下,排序顺序可能是预先配置的(例如,用户可以将其首选项设置为pending > new > complete)

推荐答案

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

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" }

Mongodb相关问答推荐

MongoDB聚合:将文档列表转换为列表

在数组对象 Mongodb 中仅 Select 需要的数组

MongoDb聚合查询问题

MongoDB 聚合 - 条件 $lookup 取决于字段是否存在

如何将交易列表变成 token 数量的对象?

MongoDB:使用数组过滤器进行更新插入

TypeError:Cannot read property '_id' of undefined

findOneAndUpdate 和 findOneAndReplace 有什么区别?

如何使用 Spring Data MongoDB 通过 GridFS ObjectId 获取二进制流

Mongoose 中不同集合的相同模式

如何使用 java 驱动程序更新 mongo db 中的文档字段?

MongoDB:多个 $elemMatch

使用已排序的数据获取不同的值

Mongodb:为什么 show dbs 不显示我的数据库?

Mongo按实际上是数字的字符串值排序

MongoDB 在 mongoengine 中使用 OR 子句

MongoDB服务器仍然可以在没有凭据的情况下访问

Lombok - java.lang.StackOverflowError:toString 方法上的 null

如何通过键名从 mongoDB 中检索值?

MongoDB:删除唯一约束