TExcelTAD
Home › MongoDB › Documents and BSON Types

Documents and BSON Types

A MongoDB document is an ordered set of field/value pairs. In mongosh you write documents as JavaScript object literals, but on disk and over the network MongoDB stores them as BSON ("binary JSON"). BSON is faster to scan than text JSON and, importantly, it has more types: separate integer and floating-point numbers, exact decimals, dates, binary data and ObjectIds.

Anatomy of a document

js
{
  _id: 1002,                                  // primary key, unique in the collection
  customerId: 3,                              // a plain number
  date: ISODate('2026-03-02T15:30:00Z'),      // a real date, not a string
  status: 'delivered',                        // a string
  items: [                                    // an array...
    { productId: 3, qty: 1, price: 27 }       // ...of embedded documents
  ],
  total: 45
}

Rules worth remembering:

  • Every document has an _id field. It must be unique in its collection and it cannot be changed after insert.
  • Field names are strings. Avoid names that start with $ and don't use . inside a name: . is how queries reach into nested documents (address.city).
  • A document can nest other documents and arrays up to 100 levels deep, and its total size is limited to 16 MB.

The common BSON types

BSON type mongosh syntax Alias for $type
String 'text' "string"
Double (64-bit float) 24.5 or 18 "double"
32-bit integer NumberInt(3) or Int32(3) "int"
64-bit integer NumberLong('9000000000') or Long(…) "long"
Decimal128 NumberDecimal('19.99') or Decimal128(…) "decimal"
Boolean true / false "bool"
Date ISODate('2026-05-01T00:00:00Z') or new Date('…') "date"
ObjectId ObjectId('…24 hex digits…') "objectId"
Array [1, 2, 3] "array"
Embedded document { city: 'Oslo' } "object"
Null null "null"

Note: A plain number typed in mongosh, such as 18, is a JavaScript number and is stored as a double. Drivers in other languages map their own integer types to int or long.

mongosh shows the non-JavaScript types with their constructor names when it prints them:

mongosh · try it yourself
db.samples.insertOne({
  _id: 'types',
  title: 'BSON demo',
  ratio: 0.75,
  count: NumberInt(12),
  views: NumberLong('9007199254740993'),
  price: NumberDecimal('19.99'),
  active: true,
  created: ISODate('2026-02-01T08:30:00Z'),
  owner: ObjectId('6650a1b2c3d4e5f601234567'),
  tags: ['a', 'b'],
  meta: { source: 'import', note: null }
});
print(db.samples.findOne());
{
  _id: 'types',
  title: 'BSON demo',
  ratio: 0.75,
  count: 12,
  views: Long('9007199254740993'),
  price: Decimal128('19.99'),
  active: true,
  created: ISODate('2026-02-01T08:30:00.000Z'),
  owner: ObjectId('6650a1b2c3d4e5f601234567'),
  tags: [ 'a', 'b' ],
  meta: { source: 'import', note: null }
}

Longs, decimals, dates and ObjectIds keep their wrapper, while a 32-bit integer comes back as an ordinary number (count: 12): mongosh converts it because every Int32 fits in a JavaScript number. The stored type is still int, so a query with $type: 'int' finds it.

Querying by type: $type

Because the same field can hold different types in different documents, MongoDB lets you filter by type. Here a sloppy import stored some quantities as strings:

mongosh · try it yourself
db.stock.insertMany([
  { _id: 1, sku: 'A1', qty: 5 },
  { _id: 2, sku: 'B2', qty: '7' },
  { _id: 3, sku: 'C3', qty: NumberInt(2) },
  { _id: 4, sku: 'D4' }
]);
print('strings:', db.stock.find({ qty: { $type: 'string' } }).toArray());
print('numbers:', db.stock.find({ qty: { $type: 'number' } }).toArray());
print('missing:', db.stock.find({ qty: { $exists: false } }).toArray());
strings: [ { _id: 2, sku: 'B2', qty: '7' } ]
numbers: [ { _id: 1, sku: 'A1', qty: 5 }, { _id: 3, sku: 'C3', qty: 2 } ]
missing: [ { _id: 4, sku: 'D4' } ]

The alias "number" matches every numeric type (double, int, long and decimal) at once.

ObjectId

When you insert a document without an _id, MongoDB generates an ObjectId: 12 bytes, shown as 24 hexadecimal digits. The first 4 bytes are the creation time in seconds, so an ObjectId roughly records when it was made:

mongosh · try it yourself
const id = ObjectId('6650a1b2c3d4e5f601234567');
print(id.toString());
print(id.getTimestamp());
6650a1b2c3d4e5f601234567
ISODate('2024-05-24T14:18:26.000Z')

ObjectIds are unique without any coordination between servers, which is why they make good default keys. In this course most examples use explicit _id values like 1 or 'types' so that the printed output is the same every time you run them; a generated ObjectId would be different on each run.

Doubles vs Decimal128 for money

Doubles are binary floating-point numbers, so some decimal fractions can't be stored exactly. For prices and other money values, Decimal128 keeps exact decimal digits:

mongosh · try it yourself
db.money.insertMany([
  { _id: 'double', a: 0.1, b: 0.2 },
  { _id: 'decimal', a: NumberDecimal('0.1'), b: NumberDecimal('0.2') }
]);
print(db.money.aggregate([{ $project: { sum: { $add: ['$a', '$b'] } } }]).toArray());
[
  { _id: 'double', sum: 0.30000000000000004 },
  { _id: 'decimal', sum: Decimal128('0.3') }
]

Tip: The sample store keeps prices as doubles to keep the examples readable. In a real shop, use Decimal128 (or store whole cents as integers).

Dates

Store dates as BSON dates, not strings. Real dates sort chronologically, compare correctly with $gt/$lt, and work with date operators such as $year and $dateToString. They are always stored in UTC.

mongosh · try it yourself
const d = db.orders.findOne({ _id: 1010 }).date;
print(d);
print(d.toISOString().slice(0, 10), d.getUTCFullYear(), d.getUTCMonth() + 1);
print(d instanceof Date);
ISODate('2026-04-09T10:05:00.000Z')
2026-04-09 2026 4
true

Test yourself

Which BSON type does mongosh use when you type the number 42?

  1. int
  2. long
  3. double
  4. decimal

What is the maximum size of a single MongoDB document?

  1. 1 MB
  2. 16 MB
  3. 64 MB
  4. Unlimited

Which query finds documents whose qty holds any kind of number?

  1. { qty: { $type: 'double' } }
  2. { qty: { $type: 'number' } }
  3. { qty: { $exists: true } }
  4. { qty: Number }