เอกสาร BSON คืออะไร
ผู้เรียนจะอ่านและเขียนเอกสาร BSON ในเชลล์ MongoDB พร้อมรู้จักชนิดฟิลด์ เช่น สตริง ตัวเลข อาร์เรย์ และออบเจ็กต์ซ้อนกัน
เอกสาร BSON คืออะไร เป็นบทเรียน MongoDB Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน MongoDB Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
JSON vs BSON: The Key Difference
You write MongoDB data as familiar JSON, but it's stored as BSON — binary JSON. It's faster to scan and supports richer types like dates and ObjectId.
The Structure of a BSON Document
A BSON document is just key-value pairs in curly braces, like a JS object. Every document needs an _id, and MongoDB auto-creates a unique one if you skip it.
// A minimal MongoDB document
{
_id: ObjectId('64a2f3b1c9e7e12345678901'),
name: 'Alice',
age: 30,
active: true
}
// _id is auto-generated if omitted on insert
// ObjectId encodes the insert timestamp in its first 4 bytesString, Number, and Boolean Fields
Most fields look like JSON: strings, numbers, true/false, and null. One tip — for money, use Decimal128 to avoid floating-point rounding errors. The code shows how.
// Explicit BSON number types in mongosh
db.products.insertOne({
name: 'Widget',
quantity: NumberInt(100), // 32-bit integer
price: NumberDecimal('9.99'), // Exact decimal for money
weight: 0.45 // Double (64-bit float)
});The Date BSON Type
Date is a real BSON type, not a string. That lets you sort and range-query by date efficiently. Never store dates as plain text — you'd lose all of that.
// Always use BSON Date, not strings
db.events.insertOne({
title: 'Conference',
startDate: new Date('2024-09-01'), // BSON Date
endDate: ISODate('2024-09-03T18:00:00Z')
});
// Range query works perfectly on Date fields:
db.events.find({ startDate: { $gte: new Date('2024-01-01') } });Nested Documents (Sub-Documents)
A field's value can be a whole document of its own — a nested document. An address fits naturally inside a user, and you query it with dot notation.
// Nested sub-document example
{
_id: ObjectId('...'),
name: 'Bob',
address: {
street: '123 Main St',
city: 'Chicago',
state: 'IL',
zip: '60601'
},
employer: {
name: 'Acme Corp',
since: ISODate('2020-03-01')
}
}
// Query by nested field:
db.users.find({ 'address.city': 'Chicago' });Arrays in BSON Documents
Arrays let one field hold a list — tags, roles, or even sub-documents. MongoDB can index each element, so checking "does this contain X?" stays fast.
// Document with arrays of primitives and sub-documents
{
_id: ObjectId('...'),
productName: 'Smart TV',
tags: ['electronics', '4K', 'HDR'],
reviews: [
{ user: 'alice', rating: 5, comment: 'Love it!' },
{ user: 'bob', rating: 4, comment: 'Good value.' }
]
}
// Query: documents where tags array contains '4K'
db.products.find({ tags: '4K' });Binary Data and ObjectId
BSON also stores raw Binary data and the special ObjectId. Neat trick: an ObjectId hides its creation time in its first bytes, so _id roughly sorts by insert order.
// Extracting timestamp from ObjectId in mongosh
const id = ObjectId('64a2f3b1c9e7e12345678901');
console.log(id.getTimestamp());
// ISODate('2023-07-03T10:15:29.000Z')
// The first 8 hex chars = 4-byte timestamp
// 64a2f3b1 = Unix epoch seconds => 2023-07-03Document Size Limit: 16 MB
Each document maxes out at 16 MB — huge for most data, and a nudge toward good modeling. For bigger files like videos, use GridFS, which splits them into chunks.
// GridFS upload example (Node.js driver)
const { GridFSBucket } = require('mongodb');
const bucket = new GridFSBucket(db, { bucketName: 'uploads' });
const uploadStream = bucket.openUploadStream('photo.jpg');
fs.createReadStream('/tmp/photo.jpg').pipe(uploadStream);
uploadStream.on('finish', () => console.log('Uploaded:', uploadStream.id));Flexible Schema in Practice
MongoDB doesn't force a schema, so two documents in one collection can have different fields. This flexible schema is a gift during fast, early development.
// Two documents in the same collection with different shapes
// This is perfectly valid in MongoDB
// User with social login
{ _id: ObjectId('...'), name: 'Alice', googleId: 'g_12345', createdAt: new Date() }
// User with email/password
{ _id: ObjectId('...'), name: 'Bob', email: 'bob@test.com', passwordHash: 'bcrypt...', createdAt: new Date() }Reading BSON in mongosh
The mongosh shell speaks a JavaScript-like syntax. Insert and it saves BSON; query and it prints clean, readable output with helpers like ObjectId and ISODate.
// mongosh: insert and read back
db.items.insertOne({ name: 'Chair', price: NumberDecimal('199.99'), createdAt: new Date() });
db.items.findOne({ name: 'Chair' });
// Output:
// {
// _id: ObjectId('64a2f3b1...'),
// name: 'Chair',
// price: Decimal128('199.99'),
// createdAt: ISODate('2024-01-15T10:23:00.000Z')
// }BSON Serialization in Node.js
With the Node.js driver you just use plain JS objects — it handles BSON conversion for you. You never build binary by hand; numbers and dates just work.
const { ObjectId, Decimal128 } = require('mongodb');
// JS object -> BSON automatically by the driver
const doc = {
_id: new ObjectId(), // BSON ObjectId
name: 'Widget', // BSON String
price: Decimal128.fromString('19.99'), // BSON Decimal128
stock: 100, // BSON Double (JS default)
createdAt: new Date(), // BSON Date
tags: ['sale', 'new'] // BSON Array
};
await db.collection('products').insertOne(doc);Quick Check
Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.
Lesson Recap
You learned BSON extends JSON with richer types, that documents nest sub-documents and arrays, and that the schema is flexible. Next: collections vs SQL tables.
คำถามที่พบบ่อย
บทเรียน “เอกสาร BSON คืออะไร” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “เอกสาร BSON คืออะไร” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส MongoDB Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “เอกสาร BSON คืออะไร”
ผู้เรียนจะอ่านและเขียนเอกสาร BSON ในเชลล์ MongoDB พร้อมรู้จักชนิดฟิลด์ เช่น สตริง ตัวเลข อาร์เรย์ และออบเจ็กต์ซ้อนกัน คุณปฏิบัติ MongoDB Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน MongoDB Academy หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน MongoDB Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “เอกสาร BSON คืออะไร” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน MongoDB Academy นี้ได้ไหม
ได้ บทเรียน MongoDB Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- เอกสาร BSON คืออะไร
- คอลเลกชันเทียบกับตาราง SQL
- ฐานข้อมูล คอลเลกชัน และเนมสเปซ
- พื้นฐานเชลล์ mongosh