Comparison/Sort Order

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

  • MinKey (internal type)
  • Null
  • Numbers (ints, longs, doubles, decimals)
  • Symbol, String
  • Object
  • Array
  • BinData
  • ObjectId
  • Boolean
  • Date
  • Timestamp
  • Regular Expression
  • MaxKey (internal type)

Numeric Types

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

Strings

Binary Comparison

By default, MongoDB uses the simple binary comparison to comparestrings.

Collation

New in version 3.4.

Collation allows users to specifylanguage-specific rules for string comparison, such as rules forlettercase and accent marks.

Collation specification has the following syntax:

  1. {
  2. locale: <string>,
  3. caseLevel: <boolean>,
  4. caseFirst: <string>,
  5. strength: <int>,
  6. numericOrdering: <boolean>,
  7. alternate: <string>,
  8. maxVariable: <string>,
  9. backwards: <boolean>
  10. }

When specifying collation, the locale field is mandatory; allother collation fields are optional. For descriptions of the fields,see Collation Document.

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

Arrays

With arrays, a less-than comparison or an ascending sort compares thesmallest element of arrays, and a greater-than comparison or adescending 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 between1 and 2. A comparison of an empty array (e.g. [ ]) treatsthe empty array as less than null or a missing field.

Objects

MongoDB’s comparison of BSON objects uses the following order:

  • Recursively compare key-value pairs in the order that they appearwithin the BSON object.
  • Compare the key field names.
  • If the key field names are equal, compare the field values.
  • If the field values are equal, compare the next key/value pair(return to step 1). An object without further pairs is less than anobject with further pairs.

Dates and Timestamps

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

Non-existent Fields

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

BinData

MongoDB sorts BinData in the following order:

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