MongoDB Academy · บทเรียน

การอัปเดตแบบตำแหน่งและแบบตำแหน่งที่กรองแล้ว

ผู้เรียนจะอัปเดตสมาชิกอาร์เรย์ที่ตรงเงื่อนไขในตำแหน่งเดิม โดยใช้ตัวดำเนินการตำแหน่ง $ และตัวดำเนินการตำแหน่งที่กรองแล้ว $[identifier]

บทเรียน 4 จาก 413 ขั้นตอน

การอัปเดตแบบตำแหน่งและแบบตำแหน่งที่กรองแล้ว เป็นบทเรียน MongoDB Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน MongoDB Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Updating Elements Inside Arrays

While $push and $pull add and remove array elements, sometimes you need to modify an existing element in place—change a field inside a sub-document that is already in the array. MongoDB provides two positional operators for this: the $ positional operator for updating the first matching element, and the $[identifier] filtered positional operator for updating all matching elements.

The $ Positional Operator

The $ positional operator acts as a placeholder for the index of the first array element that matched the query filter. You use it in the update's field path like 'arrayField.$.subField', and MongoDB replaces $ with the index of the matched element. The query filter must include a condition on the array field so MongoDB knows which element to target.

// Update the grade of the first matching scores element
db.students.updateOne(
  {
    _id: studentId,
    'scores.subject': 'math'  // match condition identifies which element
  },
  {
    $set: { 'scores.$.grade': 'A+' }  // $ = index of matched element
  }
);
// Only the FIRST element where subject='math' is updated

Limitations of the $ Operator

The $ positional operator has two important limitations: it only updates the first matching element (not all matching elements), and it cannot be used with updateMany() to safely update specific array elements across multiple documents (it updates the first match per document). For updating all matching elements or multiple documents, you need the filtered positional operator.

// Document: { scores: [{ subject: 'math', pass: false }, { subject: 'math', pass: false }] }

// $ only updates the FIRST math element
db.students.updateOne(
  { _id: id, 'scores.subject': 'math' },
  { $set: { 'scores.$.pass': true } }
);
// Result: [{ subject: 'math', pass: TRUE }, { subject: 'math', pass: FALSE }]
// Second element unchanged!

The $[] All Positional Operator

The $[] (all positional) operator updates all elements in an array without needing a filter condition. It acts as a placeholder for every element in the array. Use it when you want to apply the same update to every element of an array field—for example, resetting all flags in a status array or incrementing every score by a bonus amount.

// Give every score a +5 bonus
db.students.updateOne(
  { _id: studentId },
  { $inc: { 'scores.$[].value': 5 } }  // applies to ALL elements
);

// Set pass=true for every element in the array
db.students.updateMany(
  {},
  { $set: { 'scores.$[].reviewed': true } }  // updates across all documents
);

The $[identifier] Filtered Positional Operator

The $[identifier] filtered positional operator updates all array elements that match a condition specified in an arrayFilters option. The identifier is a placeholder name you choose (like elem or score), and the arrayFilters option defines which elements the placeholder should target. This gives you precise control over which elements get updated.

// Update ALL math scores (not just the first)
db.students.updateOne(
  { _id: studentId },
  {
    $set: { 'scores.$[elem].grade': 'A' }  // 'elem' is the identifier
  },
  {
    arrayFilters: [{ 'elem.subject': 'math' }]  // filter for 'elem'
  }
);
// All elements where subject='math' get grade='A'

Complex arrayFilters Conditions

The arrayFilters conditions support all standard MongoDB query operators: $gt, $lt, $in, $and, and more. You can define multiple identifiers for nested array updates by using multiple filter objects in the array. Each identifier must be a unique alphanumeric name starting with a lowercase letter.

// Fail all scores below 60 for a student
db.students.updateOne(
  { _id: studentId },
  { $set: { 'scores.$[lowScore].pass': false } },
  { arrayFilters: [{ 'lowScore.value': { $lt: 60 } }] }
);

// Update scores that are math AND below 70
db.students.updateOne(
  { _id: studentId },
  { $set: { 'scores.$[elem].needsHelp': true } },
  {
    arrayFilters: [{
      'elem.subject': 'math',
      'elem.value': { $lt: 70 }
    }]
  }
);

Filtered Positional With updateMany

Unlike the $ operator, $[identifier] works safely with updateMany() to apply filtered array updates across all documents in a collection. This makes it extremely powerful for bulk operations like price adjustments on specific product categories embedded in order line items, or applying a discount to certain invoice entries across all users.

// Apply 10% discount to all 'sale' items across ALL orders
db.orders.updateMany(
  {},  // all documents
  { $mul: { 'lineItems.$[item].price': 0.9 } },
  { arrayFilters: [{ 'item.category': 'sale' }] }
);

// Mark all pending tasks as 'overdue' if dueDate has passed
db.projects.updateMany(
  {},
  { $set: { 'tasks.$[t].status': 'overdue' } },
  { arrayFilters: [{ 't.status': 'pending', 't.dueDate': { $lt: new Date() } }] }
);

Nested Array Updates With Multiple Identifiers

For arrays nested inside arrays, you can use multiple identifiers in arrayFilters to target elements at different nesting levels. This is an advanced pattern—each identifier applies to a different depth in the nesting. Be mindful that deeply nested array updates are complex and may indicate a schema that could be restructured for clarity.

// Document: { courses: [{ name: 'Math', lessons: [{ id: 1, done: false }] }] }

// Mark a specific lesson as done inside a specific course
db.students.updateOne(
  { _id: studentId },
  { $set: { 'courses.$[course].lessons.$[lesson].done': true } },
  {
    arrayFilters: [
      { 'course.name': 'Math' },     // outer array filter
      { 'lesson.id': 1 }             // inner array filter
    ]
  }
);

Updating by Index With Dot Notation

When you know the exact numeric index of the element you want to update, you can use dot notation directly: 'array.2.field' updates the third element (0-indexed). This is the most direct approach when the position is known at write time. It's commonly used for fixed-position arrays where each index has a defined meaning.

// Update the third element (index 2) directly
db.results.updateOne(
  { _id: testId },
  { $set: { 'answers.2.correct': true } }  // update answer at index 2
);

// Set a specific round's score in a game
db.games.updateOne(
  { _id: gameId },
  { $set: { 'rounds.0.score': 150 } }  // update round 1 (index 0)
);

Combining Positional Operators With Other Updates

Positional operators can be combined with any update operator—$set, $inc, $unset, $push—to perform complex in-place array element modifications in a single atomic operation. For example, incrementing a nested field inside a matching array element while also updating a document-level timestamp.

// Increment attempt count for a specific question in a quiz
db.quizzes.updateOne(
  { _id: quizId, 'questions.id': 'q1' },
  {
    $inc: { 'questions.$.attemptCount': 1 },
    $set: { 'questions.$.lastAttempted': new Date(), updatedAt: new Date() }
  }
);
// All changes are atomic

When to Redesign vs Use Positional Operators

Positional updates are powerful, but complex nested positional patterns can be a sign that your schema needs rethinking. Consider restructuring when: you need to query and update elements from multiple nested arrays frequently; you find yourself writing long dot-notation paths; or your application logic must determine exact element indices at runtime. Often, moving nested data to a separate collection with references is simpler and more maintainable.

// Schema smells that suggest restructuring:
// 'courses.$[c].lessons.$[l].quizzes.$[q].answers.$.correct'
//   -> 5 levels of nesting is too complex

// Alternative: separate collections with references
// answers collection: { _id, quizId, lessonId, questionIndex, correct }

Quick Check

Test your understanding of positional and filtered positional update operators.

Lesson Recap

In this lesson you learned: $ updates the first matched array element identified by the query filter, $[] updates all array elements unconditionally, and $[identifier] with arrayFilters updates all elements matching a condition. Next up we explore the aggregation pipeline—MongoDB's powerful server-side data transformation engine.

เริ่มต้นได้ฟรี

เรียนรู้ JavaScript ด้วย AI tutor — ฟรี

เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป

คอร์ส
30
บทเรียน
120

คำถามที่พบบ่อย

บทเรียน “การอัปเดตแบบตำแหน่งและแบบตำแหน่งที่กรองแล้ว” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การอัปเดตแบบตำแหน่งและแบบตำแหน่งที่กรองแล้ว” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส MongoDB Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การอัปเดตแบบตำแหน่งและแบบตำแหน่งที่กรองแล้ว”

ผู้เรียนจะอัปเดตสมาชิกอาร์เรย์ที่ตรงเงื่อนไขในตำแหน่งเดิม โดยใช้ตัวดำเนินการตำแหน่ง $ และตัวดำเนินการตำแหน่งที่กรองแล้ว $[identifier] คุณปฏิบัติ MongoDB Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน MongoDB Academy หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน MongoDB Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน

บทเรียน “การอัปเดตแบบตำแหน่งและแบบตำแหน่งที่กรองแล้ว” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน MongoDB Academy นี้ได้ไหม

ได้ บทเรียน MongoDB Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การค้นหาอาร์เรย์: $all, $size และการจับคู่สมาชิก
  2. $elemMatch: การจับคู่เอกสารย่อยในอาร์เรย์
  3. การอัปเดตอาร์เรย์: $push, $pull, $pop, $addToSet
  4. การอัปเดตแบบตำแหน่งและแบบตำแหน่งที่กรองแล้ว
← กลับไปที่ MongoDB Academy