This is the first time I notice a $lookup to an array return the matched documents in different order, like unsorted. And I have two questions…
Firstly, why’s that?
And secondly, I ended up with this solution. This is a pipeline inside a $lookup stage, where the ‘states’ variable is an array of ObjectId.
"pipeline": [
{
"$match": {
"$expr": {
"$in": ["$_id", "$states"]
}
}
},
{
"$addFields": {
"__order": {
"$indexOfArray": ["$states", "$_id"]
}
}
},
{
"$sort": {
"__order": 1
}
},
{
"$project": {
"__order": 0
}
}
],
"as": "state"
I know that the $_id
inside the $match
stage is referring to the ‘foreign’ collection, so "$_id" "$in" "$states"
. Which is what I want.
But now. What does the second "$_id"
mean? The one inside the "$addFields"
stage.
Thank you for reading.