$

The `$` positional operator identifies an element in an array to update without explicitly specifying the position of the element in the array. The `$` operator acts as a placeholder for the first element that matches the query condition, and the array field must appear as part of the query document.

Syntax

db.collection.updateOne(
  { <array>: <value> },
  { <update operator>: { "<array>.$": <value> } }
)

Parameters

arraystringrequired

The array field that contains the element to update. Must be part of the query condition.

valuestringrequired

The value used to match the array element in the query condition.

update operatorstringrequired

The update operator to apply (for example, $set, $inc, $unset).

Examples

Sample Data

{
  "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
  "name": "First Up Consultants | Beverage Shop - Satterfieldmouth",
  "sales": {
    "totalSales": 75670,
    "salesByCategory": [
      { "categoryName": "Wine Accessories", "totalSales": 34440 },
      { "categoryName": "Bitters", "totalSales": 39496 },
      { "categoryName": "Rum", "totalSales": 1734 }
    ]
  },
  "promotionEvents": [
    {
      "eventName": "Unbeatable Bargain Bash",
      "discounts": [
        { "categoryName": "Whiskey", "discountPercentage": 7 },
        { "categoryName": "Bitters", "discountPercentage": 15 }
      ]
    }
  ]
}

Project the first element of an array matching the condition

Returns the first element within the salesByCategory array for DJ equipment with totalSales greater than 35000.

Query:

db.stores.find({
  "sales.salesByCategory": {
    $elemMatch: {
      categoryName: { $regex: "^DJ" }
    }
  },
  "sales.salesByCategory.totalSales": { $gt: 35000 }
}, {
  "sales.salesByCategory.$": 1
}).limit(2)

Output:

[
  {
    "_id": "d3c9df51-41bd-4b4e-a26b-b038d9cf8b45",
    "sales": {
      "salesByCategory": [
        { "categoryName": "DJ Speakers", "totalSales": 36972 }
      ]
    }
  }
]

Update discount percentage for a specific category

Updates the discount percentage for Desks category in the first matching promotion event.

Query:

db.stores.updateOne(
  { 
    _id: "905d1939-e03a-413e-a9c4-221f74055aac",
    "promotionEvents.discounts.categoryName": "Desks"
  },
  {
    $set: { "promotionEvents.$.discounts.$[elem].discountPercentage": 25 }
  },
  {
    arrayFilters: [{ "elem.categoryName": "Desks" }]
  }
)

Update sales category total

Updates the total sales for a specific category using the $ positional operator.

Query:

db.stores.updateOne(
  { 
    _id: "905d1939-e03a-413e-a9c4-221f74055aac",
    "sales.salesByCategory.categoryName": "Desk Lamps"
  },
  {
    $inc: { "sales.salesByCategory.$.totalSales": 1000 }
  }
)

Related