MongoDB Documents and Collections

MongoDB documents are the basic unit of data: ordered sets of field and value pairs. Related documents are stored together in a collection, much like rows in a table, and collections are grouped into databases.

A Document Example

Documents can hold strings, numbers, dates, arrays and even other documents. Notice the nested address and the tags array.

{
  _id: ObjectId('6720a4c8c2b9e81d4f3a1b03'),
  name: "Sara Khan",
  email: "sara@example.com",
  age: 29,
  address: { city: "Karachi", country: "Pakistan" },
  tags: ["vip", "newsletter"],
  joined: ISODate("2026-01-09T00:00:00Z")
}
A single document with 7 fields, one embedded document (address) and one array (tags).

BSON Data Types

MongoDB stores documents in BSON, a binary form of JSON that adds types JSON lacks.

  • String, Boolean, Null
  • Int32, Int64 (Long), Double, Decimal128 for exact money values
  • Date (stored as milliseconds since the Unix epoch)
  • ObjectId: 12-byte unique ID
  • Array and embedded Object
  • Binary data, Regular expression, Timestamp

The _id Field and ObjectId

Every document must have a unique _id. If you do not provide one, MongoDB generates an ObjectId, which includes a creation timestamp you can read back.

const id = ObjectId()
id.getTimestamp()
ISODate('2026-10-31T09:15:22.000Z')

Creating Collections

Collections are created automatically on first insert. Use createCollection when you want options such as schema validation or a capped size.

db.createCollection("logs", { capped: true, size: 1048576 })
db.getCollectionNames()
{ ok: 1 }
[ 'customers', 'logs', 'products' ]

Limits and Naming Rules

  • A single document can be at most 16 MB
  • Field names cannot contain null characters; avoid starting them with $
  • Documents can be nested up to 100 levels
  • Collection names are case sensitive

Frequently asked questions

What is the difference between JSON and BSON?

JSON is a text format. BSON is the binary format MongoDB uses internally; it is faster to scan and supports extra types such as Date, ObjectId and Decimal128.

Can I use my own value for _id?

Yes. Any unique value of any type except an array can be used, for example an email or a product SKU.

Do all documents in a collection need the same fields?

No, MongoDB has a flexible schema. In practice you should keep documents consistent, and you can enforce rules with JSON Schema validation.