How MongoDB Sorting Works for Scalar Values
· 7 min read
In this blog post, we delve into the process of sorting scalar values in MongoDB.
Sorting in MongoDB involves comparing BSON values to ascertain their relative order – whether one value is equal to, greater than, or less than another. The resultant sorted values can be in either ascending or descending order.
When comparing different BSON types, the BSON comparison order is used.
BSON comparison order
If two BSON values share the same type, their values are compared to determine which is greater or less.
However, if the BSON types are different, a predefined BSON comparison order is used.
The table below shows the predefined BSON comparison order for each BSON type.
Order of Comparison (lowest to highest) | BSON Types |
---|---|
1 | Null |
2 | Numbers (Integer, Long, Double, Decimal) |
3 | String |
4 | Object |
5 | Array |
6 | BinData |
7 | ObjectId |
8 | Boolean |
9 | Date |
10 | Timestamp |
11 | Regular Expression |