I want sort in mongodb like "order by FIELD (id, 1,3,7,8)" of mysql.
My data mongo:
* Id1: 6281c8499f2dd7e9719a780d, name : "aaa",
* Id2: 6112c8499f2dd7e9719a780d, name : "asc",
* Id3: 628dd1b4fc0fd54971b87e17, name : "123"
* ...
Code:
db.getCollection("experts").find(
{
"_id" : {
"$in" : [
ObjectId("628dd1b4fc0fd54971b87e17"),
ObjectId("6281c8499f2dd7e9719a780d"),
ObjectId("6112c8499f2dd7e9719a780d"),
....
]
}
}
).sort( ???? );
Obtained result:
"628dd1b4fc0fd54971b87e17",
"6281c8499f2dd7e9719a780d",
"6112c8499f2dd7e9719a780d"
Expected result:
* Id3: 628dd1b4fc0fd54971b87e17, name : "123"
* Id1: 6281c8499f2dd7e9719a780d, name : "aaa"
* Id2: 6112c8499f2dd7e9719a780d, name : "asc"
Dont sort field name I need sort field ID allow position array $in
2
Answers
Thanks all,
I think this solution. And work :D
As stated in my comment, this is not possible due to the nature of JSON documents. However, you can use a workaround like this:
Mongo Playground
Note, usually it is a bad design to store numeric values as string. Check Ascending/Descending Sort whether the sorting algorithm matches your requirements.