Documents and Data Types
🎯 Introduction
Previously, we used methods such as insertOne and find to perform CRUD operations. Now we will look inside a document: what its _id represents, which data types it can hold, and how fields can contain other fields.
By the end, you will understand _id and ObjectId, store and query nested documents and arrays, and recognize the basic differences between MongoDB and MySQL data modeling.
🧱 _id and ObjectId
Connect to mongosh and insert a document:
docker exec -it mongo-demo mongosh -u root -p 123456 --authenticationDatabase admin
use blog_demo
db.user.insertOne({ username: 'Xiao Ming', age: 20, city: 'Beijing' })
We did not supply _id, so MongoDB generates one automatically. Query the documents:
db.user.find()
Each document has an _id field with a value like this:
{
_id: ObjectId('665f1a2b3c4d5e6f7a8b9c0d'),
username: 'Xiao Ming',
age: 20,
city: 'Beijing'
}
_id uniquely identifies each document, serving a similar purpose to a MySQL auto-incrementing primary key. The generation mechanism differs:
- MySQL assigns auto-incrementing IDs in sequence: 1, 2, 3, and so on.
- MongoDB uses an ObjectId by default: a unique 12-byte identifier generated by a client or server without coordinating a sequence. It contains a timestamp, so values roughly increase over time, and you can extract their creation time.
_id approximates sorting by insertion time. In many cases, this avoids needing a separate field just for sorting by creation time.A common beginner mistake is querying an ObjectId-valued _id with a plain string. Wrap the string with ObjectId(); a string alone will not match:
// No match: strings and ObjectIds are different types
db.user.find({ _id: '665f1a2b3c4d5e6f7a8b9c0d' })
// Correct approach
db.user.find({ _id: ObjectId('665f1a2b3c4d5e6f7a8b9c0d') })
💡 Common Data Types
MongoDB documents are JSON-like objects, so they should feel familiar to frontend developers. Common types include:
- String:
'Xiao Ming' - Number:
20or99.5; these examples use JavaScript numeric literals for both integers and decimals. - Boolean:
trueorfalse - null: An empty value
- Date: Created with
new Date(), for example to record a registration time - Array:
['reading', 'running'] - Nested document: An object as a field value, such as
{ province: 'Zhejiang', city: 'Hangzhou' }
Insert a complete document containing several types:
db.user.insertOne({
username: 'Xiao Hong',
age: 25,
city: 'Hangzhou',
isVip: true,
deletedAt: null,
createdAt: new Date(),
address: { province: 'Zhejiang', city: 'Hangzhou' },
hobbies: ['reading', 'running'],
})
In MySQL, column types are defined when you create a table, and adding a field requires changing the table structure. MongoDB documents have no fixed structure: each document can have different fields, and you can add a field simply by including it. This flexibility is useful, but teams should still keep fields reasonably consistent to avoid disorganized data.
✨ Nested Documents
Xiao Hong's address field contains another document. This is a nested document:
address: { province: 'Zhejiang', city: 'Hangzhou' }
Think of it as a smaller folder inside a user's file: the address is a separate piece of information stored alongside the user details, so you can retrieve everything together.
Use dot notation to query a nested field:
db.user.find({ 'address.city': 'Hangzhou' })
'address.city'. Writing { address.city: 'Hangzhou' } without quotes is invalid JavaScript and causes a syntax error. This is a common mistake when first querying nested fields.You can also match a nested document as a whole, but its fields and their order must match exactly. This is less common; dot notation is the main approach to remember.
⚡ Array Fields
hobbies is an array field:
hobbies: ['reading', 'running']
MongoDB lets you query an array by an element's value without special syntax. For example, find users whose hobbies include running:
db.user.find({ hobbies: 'running' })
Any document whose array contains running matches. MongoDB checks the array elements automatically.
Use $push to append an element. Suppose Xiao Hong takes up swimming:
db.user.updateOne({ username: 'Xiao Hong' }, { $push: { hobbies: 'swimming' } })
The array becomes ['reading', 'running', 'swimming']. Without $push, you would need to read the array, append in your code, and write it back. $push does this in one operation.
⚖️ Data Modeling: Embed or Separate?
Nested documents and arrays raise a modeling question: should related data live inside one document or be stored separately?
The two databases encourage different approaches:
- MySQL commonly separates tables and uses JOIN: users and shipping addresses live in separate tables and are combined when queried. Relational tables have a flat structure, and separating data is part of normalization.
- MongoDB often uses embedding: data frequently read and written together can live in the same document. A user might have only a few shipping addresses, usually displayed with their profile, making an embedded array a good fit:
{
username: 'Xiao Ming',
addresses: [
{ label: 'home', city: 'Beijing' },
{ label: 'work', city: 'Beijing' },
],
}
Embedding lets you retrieve everything in one query: one find fetches the user and all addresses without JOINs or separate queries.
For now, focus on this basic principle. The tradeoffs become clearer as you gain practical experience.
❓ Questions and Answers
Q1: Does _id have to be an ObjectId?
No. It must be unique, but you can supply an auto-incrementing number or UUID string instead. ObjectId includes a timestamp and is easy to generate, so the default is usually sufficient.
Q2: Why use a long ObjectId instead of an auto-incrementing number?
Auto-incrementing IDs require coordinated allocation, which becomes harder across multiple machines. ObjectIds can be generated independently by clients or servers, making them well suited to MongoDB's distributed use cases.
Q3: Can dot notation access several nested levels?
Yes, for example 'address.detail.street'. Try to keep nesting to two or three levels, since deeply nested structures are harder to query and maintain.
Q4: Can $push append multiple elements at once?
Yes, with $each: { $push: { hobbies: { $each: ['swimming', 'cycling'] } } }. Appending one element is more common, so start by remembering $push.
Q5: Can an array contain nested documents?
Yes, and this is common: addresses: [{ label: 'home', city: 'Beijing' }]. Use dot notation to query them: db.user.find({ 'addresses.city': 'Beijing' }). MongoDB checks the elements of the array for a match.
🧪 Exercises
Exercise 1: Insert a user document containing username, age, a nested address document with province and city, and a hobbies array with at least two hobbies.
// Write your code here
Exercise 2: Complete the following two operations.
// 1. Find users whose address.city is Hangzhou
// Write your code here
// 2. Append swimming to the hobbies of a user found above
// Write your code here
🎉 You now understand MongoDB documents and their core data types! So far, we have entered commands in mongosh. Next, we will use the official Node.js driver to put these operations into real backend code.
