MongoDb select 全部记录并按数组排序

MongoDb select all record and order them on an array basis

在mongoDb中,我试图用聚合实现“$queryResult”中提到的结果,我想select所有记录形成一个集合 并将它们排列在一个数组上,你能帮忙吗?

在 Db 中记录

$recordsInDb = [
    ["coreId" => 10, "name" => 'a'],
    ["coreId" => 20, "name" =>'a'],
    ["coreId" => 30,"name" => 'a']
];

查询顺序

$order = [20,10];

期望的结果

$queryResult = [
    {coreId:20,name:'a'}
    {coreId:10,name:'a'},
    {coreId:30,name:'a'}
]

想不出比为集合中具有有序列表的每个文档创建一个附加数组字段更好的方法了。展开该字段并使用 $unwind operator to generate the index positions. Use that info to then sort the documents, with an additional tenary operator $condincludeArrayIndex 属性 计算逻辑表达式 array element === coreId ,并根据结果, return如果为真,则为排序索引,否则 return 常量 n > order.length

下面展示了上述方法,虽然还有很大的改进空间,但至少应该给你一些指导。当然,将管道转换为适当的驱动程序语言(我假设是 PHP)取决于您:

var order = [20, 10];
db.records.aggregate([
    { 
        "$project": {
            "coreId" : 1,
            "name" : 1,
            "sortOrder": { "$literal": order } // create an additional field
        }
    },
    { 
        "$unwind": {
            // flatten the above array
            "path": "$sortOrder", 
            // create the index position for each array element
            "includeArrayIndex": "sortIndex", 
        }
    },
    {
        "$project": {
            "coreId": 1,
            "name": 1,
            "sortIndex": {
                 "$cond": [
                    { "$eq": [ "$coreId", "$sortOrder" ] }, 
                    "$sortIndex", 999999 
                 ]
            }
        }
    },
    { "$sort": { "sortIndex": 1 } },
    {
        "$group": {
            "_id": "$coreId",
            "name": { "$first": "$name" },
            "index": { "$first": "$sortIndex" }
        }
    },
    { "$sort": { "index": 1 } },
    { 
        "$project": {
            "_id": 0,
            "coreId" : "$_id",
            "name" : 1
        }
    }
])

示例结果

/* 1 */
{
    "name" : "a",
    "coreId" : 20
}

/* 2 */
{
    "name" : "a",
    "coreId" : 10
}

/* 3 */
{
    "name" : "a",
    "coreId" : 30
}