Browse documentation
MongoDB TutorialVerified with mongodb 7.5.0

Documents, Collections, and BSON

Understand MongoDB documents, collections, ObjectId values, dates, numeric types, arrays, nested objects, and the BSON format behind them.

The MongoDB document model

A MongoDB document groups related data into one record. Fields can contain strings, booleans, numbers, dates, arrays, nested documents, binary data, and other BSON values. Documents in one collection can differ, but a consistent application-level shape makes querying and maintenance easier.

const order = {
  _id: ObjectId("66b0a2b8f20b2b4f0b17a001"),
  customer: {
    name: "Mina",
    region: "EU"
  },
  items: [
    { sku: "KB-01", quantity: 1, price: NumberDecimal("89.90") },
    { sku: "PAD-02", quantity: 2, price: NumberDecimal("14.50") }
  ],
  paid: true,
  placedAt: ISODate("2026-08-20T10:30:00Z")
};

printjson(order);

The outer value is a document. customer is an embedded document, and items is an array of embedded documents. Keeping data used together in one document can make a read both simple and atomic.

BSON is richer than JSON

MongoDB stores BSON, a binary document format with types that plain JSON does not preserve. Important examples include ObjectId, Date, Decimal128, Int32, Long, Binary, and regular expressions.

MongoG provides constructors that create real BSON values:

const sample = {
  id: ObjectId(),
  createdAt: ISODate(),
  stock: NumberInt(12),
  views: NumberLong("9007199254740993"),
  price: NumberDecimal("19.99"),
  token: UUID(),
};

printjson(sample);

Use a decimal type for exact base-10 values such as money when binary floating-point rounding is unacceptable. Use dates rather than formatted strings when you need chronological comparison and date operators.

Create and inspect typed documents

Run the following script in the tutorial database:

use("mongog_tutorial");
const products = db.collection("products");

products.deleteMany({ tutorial: "bson" });
products.insertOne({
  sku: "MONGOG-START",
  name: "Starter keyboard",
  price: NumberDecimal("79.90"),
  stock: NumberInt(8),
  tags: ["peripheral", "featured"],
  dimensions: { width: 42, depth: 13, unit: "cm" },
  availableFrom: ISODate("2026-09-01T00:00:00Z"),
  tutorial: "bson",
});

products.findOne({ sku: "MONGOG-START", tutorial: "bson" });

Expected result

MongoG displays the result as structured Extended JSON, retaining types that ordinary JSON would lose. Expanding the result shows the nested dimensions object and tags array without interpreting either as executable HTML.

Collections and consistency

A collection does not require every document to have identical fields. That flexibility supports gradual product changes and heterogeneous records, but it does not remove the need for design. Your application should define required fields, types, and invariants. MongoDB can also enforce collection-level JSON Schema validation when server-side protection is useful.

Field names are case-sensitive. customerId and CustomerId are different fields. Choose one naming convention and use it consistently in writers, indexes, and queries.

Query by BSON type

MongoDB comparisons are type-aware. Use $type to investigate a field that may have been written inconsistently:

products.find(
  {
    tutorial: "bson",
    price: { $type: "decimal" },
  },
  {
    projection: { sku: 1, price: 1, availableFrom: 1 },
  },
);

This filter matches Decimal128 prices, not strings such as "79.90" or ordinary doubles. Type inspection is useful during migrations, but consistent writers and collection validation are better long-term protections.

Dates are stored as UTC instants. The stored value does not remember a display timezone. Convert user input to a real date at the application boundary, store the instant, and apply the user’s timezone only when formatting or calculating local calendar rules.

Use Extended JSON for portable text

Plain JSON cannot represent every BSON value. Extended JSON provides a text representation that can round-trip the type:

const value = {
  id: ObjectId("66b0a2b8f20b2b4f0b17a001"),
  amount: NumberDecimal("42.10"),
  createdAt: ISODate("2026-09-01T08:00:00Z"),
};

const canonical = bson.EJSON.stringify(value, { relaxed: false });
const restored = bson.EJSON.parse(canonical);

print(canonical);
print("Restored ObjectId:", restored.id instanceof bson.ObjectId);

Canonical Extended JSON is explicit and lossless. Relaxed Extended JSON is easier to read but may render some values as ordinary JSON numbers or strings where exact type communication is less obvious. MongoG stores and transports database values in a lossless form, then applies the selected display mode.

Practice typed values

Insert one tutorial document containing an ObjectId reference, Date, Int32, Long, Decimal128, Binary value, regular expression, array, and nested document. Read it back, stringify it with canonical EJSON, parse it again, and check three constructors with instanceof.

Then intentionally query the ObjectId field with its hexadecimal string. Compare that empty result with the correct ObjectId("...") filter to make the type distinction visible.

Common mistakes

  • Comparing an ObjectId field with a plain string does not produce a type match. Convert known hexadecimal identifiers with ObjectId("...").
  • Storing dates as locale-formatted strings makes range queries and sorting unreliable. Store real dates and format them only for display.
  • Using JavaScript numbers for integers beyond the safe integer range can lose precision. Use BSON Long when the domain requires it.
  • Letting every writer invent a different field name produces a collection that is flexible but difficult to query.
  • Assuming a stored date retains the original user timezone confuses an instant with display context.
  • Exporting BSON through plain JSON.stringify() can lose or reshape types needed for a faithful round trip.

Continue learning

Use these types deliberately when you model application data, then enforce critical types with schema validation. The official manual provides a complete BSON types reference and guidance for Extended JSON.