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