Comparison/Sort Order

On this page

When comparing values of differentBSON types, MongoDB uses the following comparison order, from lowest to highest:

  1. MinKey (internal type)
  2. Null
  3. Numbers (ints, longs, doubles, decimals)
  4. Symbol, String
  5. Object
  6. Array
  7. BinData
  8. ObjectId
  9. Boolean
  10. Date
  11. Timestamp
  12. Regular Expression
  13. MaxKey (internal type)

Numeric Types

MongoDB treats some types as equivalent for comparison purposes. For instance, numeric types undergo conversion before comparison.

Strings

Binary Comparison

By default, MongoDB uses the simple binary comparison to compare strings.

Collation

New in version 3.4.

Collationallows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.

Collation specification has the following syntax:

  1. {
  2. locale
  3. :
  4. <
  5. string
  6. >
  7. ,
  8. caseLevel
  9. :
  10. <
  11. boolean
  12. >
  13. ,
  14. caseFirst
  15. :
  16. <
  17. string
  18. >
  19. ,
  20. strength
  21. :
  22. <
  23. int
  24. >
  25. ,
  26. numericOrdering
  27. :
  28. <
  29. boolean
  30. >
  31. ,
  32. alternate
  33. :
  34. <
  35. string
  36. >
  37. ,
  38. maxVariable
  39. :
  40. <
  41. string
  42. >
  43. ,
  44. backwards
  45. :
  46. <
  47. boolean
  48. >
  49. }

When specifying collation, thelocalefield is mandatory; all other collation fields are optional. For descriptions of the fields, seeCollation Document.

If no collation is specified for the collection or for the operations, MongoDB uses the simple binary comparison used in prior versions for string comparisons.

Arrays

With arrays, a less-than comparison or an ascending sort compares the smallest element of arrays, and a greater-than comparison or a descending sort compares the largest element of the arrays. As such, when comparing a field whose value is a single-element array (e.g.[1]) with non-array fields (e.g.2), the comparison is between1and2. A comparison of an empty array (e.g.[]) treats the empty array as less thannullor a missing field.

Dates and Timestamps

Changed in version 3.0.0:Date objects sort before Timestamp objects. Previously Date and Timestamp objects sorted together.

Non-existent Fields

The comparison treats a non-existent field as it would an empty BSON Object. As such, a sort on theafield in documents{}and{a:null}would treat the documents as equivalent in sort order.

BinData

MongoDB sortsBinDatain the following order:

  1. First, the length or size of the data.
  2. Then, by the BSON one-byte subtype.
  3. Finally, by the data, performing a byte-by-byte comparison.