MongoDB – Replacing Default _id with String

mongodbsorting

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

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.

Related Question