0

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?

  • Welcome to the site, what is the MongoDB version(x,y,z)? – Md Haidar Ali Khan Apr 16 at 10:48
  • 2
    If you want to sort them as numbers, why are you storing them as strings? – mustaccio Apr 16 at 11:32
0

What's my option? Is there any way to sort the string like a number?

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.

 db.collection.aggregate(
[
    {
        '$addFields': {
            '_id': {
                '$toInt': '$_id'
            }
        }
    }, {
        '$sort': {
            '_id': 1
        }
    }
]
)

Or I have to change my _id type?

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.