Nadav
Nadav

Reputation: 1145

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

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 that array.

For example if I provided Mongoose with this array ["112", "111", "113"] and assuming that all the documents with these IDs exist the result will be an array of documents ordered accordingly as: [{//112},{//111},{//113}]

Just to be crystal clear, I don't need to sort the array by any specific document field - I am looking for a way to tell Mongoose to sort by the order of the IDs as presented in the conditions array itself. Is this possible?

Upvotes: 1

Views: 398

Answers (1)

mickl
mickl

Reputation: 49945

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

Upvotes: 1

Related Questions