0
0
MongodbHow-ToBeginner · 3 min read

How to Use $ Positional Operator in MongoDB: Syntax and Examples

In MongoDB, the $ positional operator is used to update the first array element that matches a query condition. It allows you to modify a specific element inside an array without updating the entire array.
📐

Syntax

The $ positional operator is used in update queries to target the first matching element in an array. It is placed inside the update document to specify which array element to update.

  • { 'arrayField.$': value }: Updates the matched element in arrayField.
  • Used with a query that matches an element inside the array.
mongodb
db.collection.updateOne(
  { 'arrayField.key': valueToMatch },
  { $set: { 'arrayField.$.fieldToUpdate': newValue } }
)
💻

Example

This example updates the score of the first grade with type equal to "quiz" in the grades array of a student document.

mongodb
db.students.updateOne(
  { 'grades.type': 'quiz' },
  { $set: { 'grades.$.score': 95 } }
)

// Document before update:
// {
//   _id: 1,
//   name: "John",
//   grades: [
//     { type: "exam", score: 88 },
//     { type: "quiz", score: 80 },
//     { type: "quiz", score: 85 }
//   ]
// }

// Document after update:
// {
//   _id: 1,
//   name: "John",
//   grades: [
//     { type: "exam", score: 88 },
//     { type: "quiz", score: 95 },  // updated
//     { type: "quiz", score: 85 }
//   ]
// }
Output
{ acknowledged: true, matchedCount: 1, modifiedCount: 1 }
⚠️

Common Pitfalls

Common mistakes when using the $ positional operator include:

  • Trying to update multiple matching array elements at once (the $ operator only updates the first match).
  • Using $ without a proper query that matches an array element.
  • Confusing $ with $[] which updates all elements.

Example of wrong usage and correct usage:

mongodb
// Wrong: No array element matched in query
// This will not update anything

db.students.updateOne(
  { name: "John" },
  { $set: { 'grades.$.score': 100 } }
)

// Correct: Query matches an array element

db.students.updateOne(
  { 'grades.type': 'quiz' },
  { $set: { 'grades.$.score': 100 } }
)
📊

Quick Reference

  • $: Updates the first matching array element.
  • $[]: Updates all elements in the array.
  • $[]: Updates array elements that match a filter condition.
  • Always use a query that matches an array element to use $.

Key Takeaways

The $ positional operator updates the first matching element in an array.
You must include a query that matches an array element to use $ correctly.
$ updates only one element; use $[] to update all elements.
Common errors include missing array match in the query or expecting multiple updates with $.
Use $[] for conditional updates on multiple array elements.