I replace MongoDB default _id with type string. And now I want to sort my collections, the result _id after sort is:
1
10
100
101
2
20
200
I want the result like sorting number which is:
1
2
3
4
5
What's my option? Is there any way to sort the string like number? Or I have to change my _id type?
Best Answer
Yes, you have an option to sort string like a number, but in all your queries you need to convert your string field to an integer field just for sorting and it is not recommended.
Yes, you need to change the type of _id field from string to integer as a permanent solution. Since _id filed is an immutable field, you cannot directly convert the data of _id field from string to integer. you need to remove all your documents and insert with the corrected data type.