Rare Types and the Sort Order
Most fields you design will be strings, numbers, booleans, dates, objects and arrays. The remaining BSON types are rarer, but you will meet them in other people's data, and one idea from this lesson, the type order, explains some of the strangest query results you will ever see.
The rule
Every type has a rank: MinKey lowest, MaxKey highest, everything else between.
The rarer types, briefly:
- Binary data (
BinData): raw bytes, such as a small thumbnail or a hash. A subtype marks what they are; subtype 4 is a UUID, created in mongosh withUUID(). - Regular expression: a pattern. You mostly use it in queries:
{ title: /^The/ }finds The Hobbit. Patterns are case-sensitive unless you add theiflag. - JavaScript (code): a stored function. Rare today; do not keep app logic in documents.
- Symbol and Undefined: deprecated leftovers. Do not create them; treat them as data to clean up.
- MinKey and MaxKey: special values that compare below and above every other value. MongoDB uses them internally, for example to mark the open ends of a range.
When MongoDB compares values of different types, it ranks the types in this order, lowest first:
MinKey → Null → Numbers → String → Object → Array → Binary data → ObjectId → Boolean → Date → Timestamp → Regular expression → MaxKey
A missing field sorts like null. All numeric types share one rank and compare by value.