การฉายผลฟิลด์ซ้อนกันและฟิลด์อาร์เรย์
ผู้เรียนจะใช้รูปแบบจุดและตัวดำเนินการ $slice เพื่อฉายผลบางส่วนของอาร์เรย์และเอกสารย่อยที่ซ้อนกัน
การฉายผลฟิลด์ซ้อนกันและฟิลด์อาร์เรย์ เป็นบทเรียน MongoDB Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน MongoDB Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Projecting Nested Fields With Dot Notation
To project a specific field from an embedded sub-document, use dot notation in the projection key. For example, if a document has an address sub-document, you can project only address.city without returning the full address object. MongoDB traverses the nested path and returns only the specified leaf field, keeping the parent field wrapper in the result.
// Document shape: { name, address: { street, city, zip }, email }
const user = await db.collection('users').findOne(
{ email: 'alice@example.com' },
{ projection: { name: 1, 'address.city': 1, _id: 0 } }
);
// Result: { name: 'Alice', address: { city: 'Austin' } }
// street and zip are excluded; only city is returned inside addressExcluding Nested Fields
Just as with top-level fields, you can exclude specific nested fields while returning the rest of the sub-document. Using 'address.zip': 0 returns the entire address object except the zip field. This is useful for hiding internal-use sub-fields while exposing the rest of a nested object to the client.
// Return everything except address.zip
const user = await db.collection('users').findOne(
{ email: 'alice@example.com' },
{ projection: { 'address.zip': 0, passwordHash: 0 } }
);
// Result includes address.street and address.city but not address.zipArray Fields in Projections
When a projected field is an array, MongoDB returns the entire array by default. If a user document has a tags array with ten elements, projecting tags: 1 returns all ten. To control how much of an array is returned, you need $slice, $, or $elemMatch—the three array-specific projection operators.
// Returns the entire tags array
const post = await db.collection('posts').findOne(
{ slug: 'intro-to-mongodb' },
{ projection: { title: 1, tags: 1, _id: 0 } }
);
// Result: { title: '...', tags: ['mongodb', 'nosql', 'tutorial', ...] }Slicing Arrays With $slice
The $slice projection operator limits the number of array elements returned. Pass a positive integer to return the first N elements, or a negative integer to return the last N elements. You can also pass a two-element array [skip, limit] to skip a number of elements and then return the next N. $slice is the simplest way to paginate or preview array contents.
// Return only the first 3 comments from a post
db.posts.findOne(
{ slug: 'intro-to-mongodb' },
{ projection: { title: 1, comments: { $slice: 3 } } }
);
// Return the last 5 comments
db.posts.findOne(
{ slug: 'intro-to-mongodb' },
{ projection: { title: 1, comments: { $slice: -5 } } }
);
// Skip 10 comments, then return the next 5
db.posts.findOne(
{ slug: 'intro-to-mongodb' },
{ projection: { title: 1, comments: { $slice: [10, 5] } } }
);Projecting Nested Array Sub-Fields
You can project a field inside an array of sub-documents using dot notation in an inclusion projection. For example, an orders document might have an items array where each element has productId, qty, and price. Projecting 'items.qty': 1 returns the entire items array but with only the qty field inside each element.
// Return items array with only the qty field in each element
db.orders.findOne(
{ _id: ObjectId('o1') },
{ projection: { 'items.qty': 1, 'items.productId': 1, _id: 0 } }
);
// Result:
// { items: [{ productId: ObjectId('p1'), qty: 2 }, { productId: ObjectId('p2'), qty: 1 }] }Excluding a Nested Array Sub-Field
Similarly, you can exclude specific sub-fields from array elements. For example, an employees collection might store salary inside a compensation sub-document within each element of an array. Projecting 'positions.compensation': 0 returns the positions array with the sensitive compensation data stripped from each element.
// Exclude compensation from every element of the positions array
db.employees.findOne(
{ name: 'Alice' },
{ projection: { 'positions.compensation': 0 } }
);Projecting Multiple Nested Paths
You can project multiple nested fields from the same sub-document or array in one projection. Each dot-notation path is independent. This composability lets you extract precisely the sub-tree of a document that your query needs, without bringing back irrelevant nested data that would inflate the response.
// Get shipping address city and order total only
db.orders.find(
{ status: 'shipped' },
{
projection: {
'shippingAddress.city': 1,
'shippingAddress.country': 1,
total: 1,
_id: 0
}
}
);Deeply Nested Dot Notation
Dot notation can go multiple levels deep. If you have a document with meta.seo.keywords, you can project exactly that path. MongoDB will return the outer wrapper fields (meta and seo) but only include the keywords leaf, stripping all other sibling fields at each level.
// Document: { title, meta: { seo: { keywords: [...], description: '...' }, author: '...' } }
db.articles.findOne(
{ slug: 'my-article' },
{ projection: { title: 1, 'meta.seo.keywords': 1, _id: 0 } }
);
// Result: { title: '...', meta: { seo: { keywords: [...] } } }
// meta.seo.description and meta.author are excludedProjection and Index Coverage for Nested Fields
For a query to be covered (served entirely from the index without touching documents), the projection must include only fields present in the index, including nested fields. A compound index on { 'address.city': 1, name: 1 } can cover a query that filters on address.city and projects only address.city and name (with _id: 0). Covered queries achieve the lowest possible latency.
// Create an index on nested field
db.users.createIndex({ 'address.city': 1, name: 1 });
// Covered query — both filter and projection are inside the index
db.users.find(
{ 'address.city': 'Austin' },
{ projection: { 'address.city': 1, name: 1, _id: 0 } }
).explain('executionStats');
// totalDocsExamined should be 0$slice in Mongoose
Mongoose does not have a native $slice shorthand on the query builder, but you can pass a projection object directly. Use { fieldName: { $slice: N } } inside the Mongoose .select() call if you pass an object, or pass the projection as the second argument to .find(). The driver forwards it to MongoDB unchanged.
// Mongoose: return title and first 5 comments using $slice
const post = await Post.findOne(
{ slug: 'intro-to-mongodb' },
{ title: 1, comments: { $slice: 5 }, _id: 0 }
);
// Alternatively as a Mongoose query
const post2 = await Post
.findOne({ slug: 'intro-to-mongodb' })
.select({ title: 1, comments: { $slice: 5 }, _id: 0 });Nested Projection Gotchas
A common gotcha: projecting a nested field in an array requires you to use dot notation, but MongoDB returns the full array wrapper. You cannot project individual array elements by index (e.g., items.0 doesn't filter to just the first element in the projection—use $slice: 1 for that). Also, you cannot mix projecting a parent field and a child field in the same path: either project address or address.city, not both.
Quick Check
Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.
Lesson Recap
In this lesson you learned: dot notation projects specific nested fields from sub-documents and arrays, $slice limits the number of array elements returned, and projecting nested array sub-fields includes only the specified leaf inside each array element. Next up we explore the $ and $elemMatch array projections for returning a single matching element from an array.
คำถามที่พบบ่อย
บทเรียน “การฉายผลฟิลด์ซ้อนกันและฟิลด์อาร์เรย์” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การฉายผลฟิลด์ซ้อนกันและฟิลด์อาร์เรย์” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส MongoDB Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การฉายผลฟิลด์ซ้อนกันและฟิลด์อาร์เรย์”
ผู้เรียนจะใช้รูปแบบจุดและตัวดำเนินการ $slice เพื่อฉายผลบางส่วนของอาร์เรย์และเอกสารย่อยที่ซ้อนกัน คุณปฏิบัติ MongoDB Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน MongoDB Academy หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน MongoDB Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “การฉายผลฟิลด์ซ้อนกันและฟิลด์อาร์เรย์” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน MongoDB Academy นี้ได้ไหม
ได้ บทเรียน MongoDB Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การฉายผลแบบรวมหรือแบบตัดออก
- การฉายผลฟิลด์ซ้อนกันและฟิลด์อาร์เรย์
- การฉายผลอาร์เรย์ด้วย $ และ $elemMatch
- แนวทางปฏิบัติที่ดีในการฉายผลสำหรับการตอบกลับ API