MongoDB Documents
What Is Documents?
A document is the basic unit of data in MongoDB. It is a set of field-and-value pairs that looks a lot like JSON, but it is stored on disk as BSON (Binary JSON), which adds extra types such as Date, ObjectId, Decimal128, and Int32/Long. Documents live inside collections, and a single document can hold nested documents and arrays, so related data can sit together in one record.
Why It Matters
| Reason | Benefit |
|---|---|
| Maps to application objects | A document closely matches an object or dictionary in your code, so there is little translation work. |
| Related data stays together | Embedding addresses, tags, or line items avoids joins for the most common reads. |
| Flexible shape | You can add a field to new documents without migrating every existing one. |
| Rich types | BSON dates, decimals, and binary data are first-class, not strings pretending to be something else. |
| Predictable identity | The unique _id gives every document a stable handle for lookups and references. |
How To Use It
- Open mongosh and switch to a practice database with use shop.
- Write a document as a JavaScript-style object with a few scalar fields.
- Add a nested document (for example address) and an array (for example tags).
- Insert it with db.customers.insertOne(...) and read the returned insertedId.
- Run db.customers.findOne() to see the stored document including _id.
- Use dot notation such as db.customers.find({ "address.city": "Pune" }) to query inside the nested document.
- Try inserting a document with your own _id and then repeat it to see the duplicate key error.
mongosh Examples
use shop
db.customers.insertOne({
name: "Asha Rao",
email: "[email protected]",
age: 29,
joinedAt: new Date("2026-01-15"),
address: { city: "Pune", country: "IN" },
tags: ["newsletter", "premium"]
})
db.customers.findOne({ email: "[email protected]" })
// Query inside a nested document with dot notation
db.customers.find({ "address.city": "Pune" })
// Supply your own _id instead of an ObjectId
db.settings.insertOne({ _id: "theme", value: "dark" }) Edge Cases & Pitfalls
Field order matters for equality
Two documents with the same fields in a different order are not equal when you match an embedded document exactly. Prefer dot notation for nested matches.
_id cannot be changed
You cannot update _id on an existing document. To change it, insert a new document and delete the old one.
Documents can grow too large
Unbounded arrays can push a document past the 16 MiB limit. Model growing lists as separate documents.
Dots and dollar signs in field names
Field names with . or a leading $ are legal in recent versions but awkward to query and update. Avoid them.
Cheat Sheet
| Topic | Detail |
|---|---|
| Document | An ordered set of field: value pairs written like { name: "Ada", age: 36 } |
| Field name | A string key; avoid starting with $ and avoid dots in names |
| _id | Required, unique within the collection, immutable, and always indexed |
| ObjectId | 12-byte default _id type that embeds a creation timestamp |
| Nested document | A field whose value is another document, accessed with dot notation: address.city |
| Array | A field holding a list of values or documents: tags: ["db", "nosql"] |
| Date | Stored as a BSON Date; create with new Date() or ISODate() in mongosh |
| Max size | 16 MiB per document; use references or GridFS for larger data |
| Schema | Flexible by default: documents in one collection can differ in shape |
Key Takeaways
Every document has a unique _id field. If you do not supply one, the driver or server generates an ObjectId for you. The maximum BSON document size is 16 MiB.
Frequently Asked Questions
What is the difference between JSON and BSON?
JSON is a text format. BSON is the binary format MongoDB uses to store and transmit data. BSON supports extra types such as Date, ObjectId, Decimal128, and binary data, and is faster to traverse.
Is _id required?
Yes. Every document must have a unique _id. If you omit it on insert, MongoDB generates an ObjectId for you.
Can _id be something other than an ObjectId?
Yes. It can be a string, number, UUID, or another document, as long as it is unique in the collection and is not an array.
Do all documents in a collection need the same fields?
No. MongoDB does not force a shape by default, although you can add schema validation rules to a collection when you want consistency.
How big can a document be?
The BSON document size limit is 16 mebibytes. For larger files, use GridFS or store the file elsewhere and keep a reference.
How do I read a nested field?
Use dot notation in quotes, such as db.customers.find({ "address.city": "Pune" }). The same notation works in projections and updates.
Next: MongoDB Databases
Continue the MongoDB learning path.
CODETOFUN NEWS
Stay Ahead in Tech
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
8 people found this page helpful
