Reputation: 611
let say I have documents
[
{
score : 3,
},
{
score : 1,
},
{
score : 2,
}
]
and an array contain order of score
const array = [2,1,3]
How can I sort documents by order of array
expected result :
[
{
score : 2,
},
{
score : 1,
},
{
score : 3,
}
]
Upvotes: 0
Views: 62
Reputation: 10525
Using indexOfArray
db.collection.aggregate([
{
$addFields: {
"order": {
$indexOfArray: [[2,1,3], "$score"]
}
}
},
{
$sort: {
"order": 1
}
}
]);
Upvotes: 1