Sorting query results by the order of items in provided conditions array in Mongoose

前端 未结 1 376
天涯浪人
天涯浪人 2021-01-27 00:09

I am looking for a way to query a database with Mongoose based on an array of document IDs and return the results in the order in which they were presented to Mongoose within th

相关标签:
1条回答
  • 2021-01-27 01:08

    Considering following data:

    db.col.save({ a: "111"})
    db.col.save({ a: "112"})
    db.col.save({ a: "113"})
    db.col.save({ a: "114"})
    

    you can use Aggregation Framework's $match to filter out all the items that are not present in specified array and the $addFields with $indexOfArray to get the index property. Then you can $sort by that property and use $project to remove temporary field. Try:

    db.col.aggregate([
        {
            $match: { a: { $in: ["112", "111", "113"] } }
        },
        {
            $addFields: {
                index: { $indexOfArray: [ ["112", "111", "113"], "$a" ] }
            }
        },
        {
            $sort: { index: 1 }
        },
        {
            $project: { index: 0, _id: 0 }
        }
    ])
    

    Outputs:

    { "a" : "112" }
    { "a" : "111" }
    { "a" : "113" }
    
    0 讨论(0)
提交回复
热议问题