การฉายผลแบบรวมหรือแบบตัดออก
ผู้เรียนจะเลือกหรือซ่อนฟิลด์เฉพาะในผลลัพธ์คิวรี และเข้าใจว่าเหตุใดจึงผสมการรวมฟิลด์กับการตัดฟิลด์ออกในการฉายผลเดียวกันไม่ได้
การฉายผลแบบรวมหรือแบบตัดออก เป็นบทเรียน MongoDB Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน MongoDB Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
What Is a Projection?
A projection is the second argument to find() or findOne() that tells MongoDB which fields to include or exclude from the result. Instead of returning the entire document, you specify exactly the fields you need. This reduces bandwidth, decreases memory usage in your application, and keeps API responses lean. Projections are one of the simplest and most impactful query optimisations available.
Inclusion Mode: Specify What to Return
In inclusion mode, you list the fields you want to receive and set their value to 1. MongoDB returns only those fields plus _id (which is included by default). This is the most common form of projection because it explicitly declares the fields your query depends on, making the intent clear to anyone reading the code.
// Return only name and email — everything else is excluded
const user = await db.collection('users').findOne(
{ email: 'alice@example.com' },
{ projection: { name: 1, email: 1 } }
);
// Result: { _id: ObjectId('...'), name: 'Alice', email: 'alice@example.com' }Excluding _id From Results
The _id field is always included in inclusion projections unless you explicitly exclude it. Set _id: 0 alongside inclusion fields to suppress it. This is useful when building API responses that use a different identifier field, or when you want to avoid leaking internal MongoDB IDs to clients.
// Include name and email but suppress _id
const user = await db.collection('users').findOne(
{ email: 'alice@example.com' },
{ projection: { _id: 0, name: 1, email: 1 } }
);
// Result: { name: 'Alice', email: 'alice@example.com' }
// _id is not presentExclusion Mode: Specify What to Omit
In exclusion mode, you set fields to 0 to remove them from the result. Every other field is returned. This is useful when you want almost all fields but need to suppress a few sensitive or large ones—for example, hiding a passwordHash field from query results in a general-purpose user query.
// Return all user fields EXCEPT passwordHash and internalNotes
const user = await db.collection('users').findOne(
{ email: 'alice@example.com' },
{ projection: { passwordHash: 0, internalNotes: 0 } }
);
// Result: everything except passwordHash and internalNotesCannot Mix Inclusion and Exclusion
MongoDB does not allow mixing inclusion (1) and exclusion (0) fields in a single projection, except for the _id field. Attempting to do so results in a Projection cannot have a mix of inclusion and exclusion fields error. Choose one mode per query. The only legal combination is inclusion fields (1) with _id: 0.
// VALID: inclusion mode with _id suppressed
{ projection: { name: 1, email: 1, _id: 0 } }
// VALID: exclusion mode
{ projection: { passwordHash: 0, secret: 0 } }
// INVALID: mixing 1 and 0 (throws an error)
// { projection: { name: 1, passwordHash: 0 } } <- ERRORProjections in find() vs Aggregation
In find(), projection is the second argument. In the aggregation pipeline, you use the $project stage, which supports the same inclusion/exclusion syntax plus computed fields and expressions. Both behave the same way with respect to the cannot-mix rule, but $project is more powerful because it can rename fields and add calculated values.
// find() projection
db.users.find({}, { name: 1, email: 1, _id: 0 });
// Equivalent in aggregation with $project
db.users.aggregate([
{ $project: { name: 1, email: 1, _id: 0 } }
]);Projections and Covered Queries
A covered query is a query where both the filter fields and the projection fields are entirely within a single index. MongoDB can answer a covered query from the index alone without reading the actual document from disk. Projections are essential for covered queries: if you project a field not in the index, MongoDB must fetch the document, breaking the coverage benefit.
// Index on { email: 1, name: 1 }
db.users.createIndex({ email: 1, name: 1 });
// Covered query — filter + projection both satisfied by the index
db.users.find(
{ email: 'alice@example.com' },
{ name: 1, email: 1, _id: 0 } // _id must be excluded for full coverage
).explain('executionStats');
// Look for 'totalDocsExamined: 0' in the outputProjections With Mongoose
In Mongoose, you can pass a projection string or object to .select(). A space-separated string with + for inclusion and - for exclusion is common. Fields marked with select: false in the schema (like passwordHash) are excluded from results by default and must be explicitly included with +passwordHash.
// Mongoose: string projection (+ include, - exclude)
const users = await User.find({}).select('name email -_id');
// Object projection
const user = await User.findOne({ email: 'a@b.com' }).select({ name: 1, email: 1, _id: 0 });
// Schema-level default exclusion
const userSchema = new mongoose.Schema({
email: String,
passwordHash: { type: String, select: false } // excluded by default
});Projection Performance Benefits
Projections improve performance in three ways: (1) they reduce the amount of data read from disk when the projection aligns with an index; (2) they reduce network bandwidth between the MongoDB server and your application; (3) they reduce the amount of memory your application must allocate to hold query results. For large documents or high-throughput APIs, projections can reduce response size by 80% or more.
Projecting Computed Values in Aggregation
The $project stage in aggregation goes beyond simple inclusion/exclusion. You can compute new fields using expressions—for example, concatenating strings, performing arithmetic, or extracting parts of a date. This lets you transform the shape of documents server-side before sending results to the application, reducing client-side processing.
db.orders.aggregate([
{
$project: {
orderId: '$_id',
_id: 0,
totalWithTax: { $multiply: ['$subtotal', 1.1] }, // computed field
year: { $year: '$createdAt' } // date extraction
}
}
]);Always Project Sensitive Fields Out
Never return sensitive fields like passwordHash, apiKey, ssn, or creditCardNumber in general-purpose queries. Use exclusion projections or schema-level select: false to ensure these fields never accidentally appear in API responses. Defence in depth means applying projections at the data layer as a backstop, even if the application already strips these fields from responses.
Quick Check
Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.
Lesson Recap
In this lesson you learned: inclusion projections (value 1) return only listed fields, exclusion projections (value 0) return all fields except the listed ones, and you cannot mix inclusion and exclusion except for _id: 0 with inclusion fields. Next up we explore projecting nested fields and arrays using dot notation and $slice.
เรียนรู้ JavaScript ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 30
- บทเรียน
- 120
คำถามที่พบบ่อย
บทเรียน “การฉายผลแบบรวมหรือแบบตัดออก” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การฉายผลแบบรวมหรือแบบตัดออก” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส MongoDB Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การฉายผลแบบรวมหรือแบบตัดออก”
ผู้เรียนจะเลือกหรือซ่อนฟิลด์เฉพาะในผลลัพธ์คิวรี และเข้าใจว่าเหตุใดจึงผสมการรวมฟิลด์กับการตัดฟิลด์ออกในการฉายผลเดียวกันไม่ได้ คุณปฏิบัติ MongoDB Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน MongoDB Academy หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน MongoDB Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “การฉายผลแบบรวมหรือแบบตัดออก” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน MongoDB Academy นี้ได้ไหม
ได้ บทเรียน MongoDB Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การฉายผลแบบรวมหรือแบบตัดออก
- การฉายผลฟิลด์ซ้อนกันและฟิลด์อาร์เรย์
- การฉายผลอาร์เรย์ด้วย $ และ $elemMatch
- แนวทางปฏิบัติที่ดีในการฉายผลสำหรับการตอบกลับ API