Nous pouvons utiliser $indexOfArray
Console
db.collectionName.aggregate([{
$match: {
_id: {
$in: [249, 244]
}
}
}, {
$addFields: {
sort: {
$indexOfArray: [
[249, 244], "$_id"
]
}
}
},{
$sort: {
sort: 1
}
}])
Code PHP
$data = $this->mongo->{$collectionName}->aggregate(
[
[
'$match' => ['_id' => ['$in' => $idList]]
],
[
'$addFields' => ['sort' => ['$indexOfArray' => [$idList, '$_id']]]
],
[
'$sort' => ['sort' => 1]
],
[
'$project' => [
'name' => 1
]
]
]
);