根据mongodb中的多个字段对集合进行排序

时间:2019-04-11 19:56:25

标签: mongodb

我有一个需要根据不同字段对集合进行排序的要求。以下是我的数据库条目

db.requests.find()

{ "_id" : ObjectId("5caf805f50ca58361589924b"),"type" : "adhoc",  "immediate" : false, "place": "london"}
{ "_id" : ObjectId("5c947e37015bfe78a80e5349"),"type" : "adhoc",  "immediate" : true, "place": "tokoy" }
{ "_id" : ObjectId("5c9481fa015bfe78a80e534d"),"type" : "periodic",  "immediate" : false , "place": "bangalore"}
{ "_id" : ObjectId("5c94ae95015bfe78a80e5363"),"type" : "adhoc",  "immediate" : true, "place": "lanka"}
{ "_id" : ObjectId("5c875a96015bfe7b5e772ea3"),"type" : "adhoc",  "immediate" : false, "place": "jakarta"}
{ "_id" : ObjectId("5c9481fa015bfe78a80e534d"),"type" : "periodic",  "immediate" : false , "place": "europe"}

考虑        如果“类型”为“临时”,则“立即”可以为“真”或“假”。        如果“类型”为“定期”,则“立即”将始终为“假”

我只想按以下顺序获得结果:

  1. 所有带有“ immediate”的条目:“ true”

  2. 所有带有“ type”:“ adhoc”和“ immediate”:“ false”的条目

  3. 所有带有“ type”:“ periodic”的条目

结果应类似于:

        { "_id" : ObjectId("5c947e37015bfe78a80e5349"),"type" : "adhoc",  "immediate" : true, "place": "tokoy" }
        { "_id" : ObjectId("5c94ae95015bfe78a80e5363"),"type" : "adhoc",  "immediate" : true, "place": "lanka"}
        { "_id" : ObjectId("5caf805f50ca58361589924b"),"type" : "adhoc",  "immediate" : false, "place": "london"}
        { "_id" : ObjectId("5c875a96015bfe7b5e772ea3"),"type" : "adhoc",  "immediate" : false, "place": "jakarta"}
        { "_id" : ObjectId("5c9481fa015bfe78a80e534d"),"type" : "periodic",  "immediate" : false , "place": "bangalore"}
        { "_id" : ObjectId("5c9481fa015bfe78a80e534d"),"type" : "periodic",  "immediate" : false , "place": "europe"}

1 个答案:

答案 0 :(得分:0)

您可以将其视为得分问题-您需要根据自己的条件计算得分,然后根据该得分$sort。为了使算法可读,可以使用$switch定义每种情况:

db.requests.aggregate([
    {
        $addFields: {
            score: {
                $switch: {
                    branches: [
                        { case: { $eq: [ "$immediate", true ] }, then: 3 },
                        { case: { $eq: [ "$type", "adhoc" ] }, then: 2 },
                        { case: { $eq: [ "$type", "periodic" ] }, then: 1 }
                    ],
                    default: 0
                }
            }
        }
    },
    {
        $sort: {
            score: -1
        }
    }
])