MongodDB: BSON Types

  • The $type operator supports using these values to query fields by their BSON type. $type also supports the number alias, which matches the integer, decimal, double, and long BSON types.
  • The $type aggregation operator returns the BSON type of its argument.
  • The $isNumber aggregation operator returns true if its argument is a BSON integer, decimal, double, or long. New in version 4.4

Binary Data

A BSON binary binData value is a byte array. A binData value has a subtype that indicates how to interpret the binary data. The following table shows the subtypes.

ObjectId

ObjectIds are small, likely unique, fast to generate, and ordered. ObjectId values are 12 bytes in length, consisting of:

  • A 4-byte timestamp, representing the ObjectId’s creation, measured in seconds since the Unix epoch.
  • A 5-byte random value generated once per process. This random value is unique to the machine and process.
  • A 3-byte incrementing counter, initialized to a random value.
  • in mongosh, you can access the creation time of the ObjectId, using the ObjectId.getTimestamp() method.
  • sorting on an _id field that stores ObjectId values is roughly equivalent to sorting by creation time.

String

BSON strings are UTF-8. In general, drivers for each programming language convert from the language’s string format to UTF-8 when serializing and deserializing BSON. This makes it possible to store most international characters in BSON strings with ease. [1] In addition, MongoDB $regex queries support UTF-8 in the regex string.

Timestamps

BSON has a special timestamp type for internal MongoDB use and is not associated with the regular Date type. This internal timestamp type is a 64 bit value where:

  • the most significant 32 bits are a time_t value (seconds since the Unix epoch)
  • the least significant 32 bits are an incrementing ordinal for operations within a given second.

Date

BSON Date is a 64-bit integer that represents the number of milliseconds since the Unix epoch (Jan 1, 1970). This results in a representable date range of about 290 million years into the past and future.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store