你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

$ (位置运算符)

适用对象: MongoDB vCore

$位置运算符标识要更新的数组中的元素,而无需显式指定数组中元素的位置。 运算符 $ 充当与查询条件匹配的第一个元素的占位符,并且数组字段必须作为查询文档的一部分显示。

语法

位置运算符的 $ 语法如下所示:

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

参数

DESCRIPTION
array 包含要更新的元素的数组字段。 必须是查询条件的一部分。
value 用于匹配查询条件中的数组元素的值。
update operator 要应用的更新运算符(例如, $set$inc$unset)。

示例:

让我们了解数据集中示例 JSON 的 stores 用法。

{
  "_id": "905d1939-e03a-413e-a9c4-221f74055aac",
  "name": "Trey Research | Home Office Depot - Lake Freeda",
  "location": { "lat": -48.9752, "lon": -141.6816 },
  "staff": { "employeeCount": { "fullTime": 12, "partTime": 19 } },
  "sales": {
    "salesByCategory": [ { "categoryName": "Desk Lamps", "totalSales": 37978 } ],
    "revenue": 37978
  },
  "promotionEvents": [
    {
      "eventName": "Crazy Deal Days",
      "promotionalDates": {
        "startDate": { "Year": 2023, "Month": 9, "Day": 27 },
        "endDate": { "Year": 2023, "Month": 10, "Day": 4 }
      },
      "discounts": [
        { "categoryName": "Desks", "discountPercentage": 22 },
        { "categoryName": "Filing Cabinets", "discountPercentage": 23 }
      ]
    },
    {
      "eventName": "Incredible Markdown Mania",
      "promotionalDates": {
        "startDate": { "Year": 2023, "Month": 12, "Day": 26 },
        "endDate": { "Year": 2024, "Month": 1, "Day": 2 }
      },
      "discounts": [
        { "categoryName": "Monitor Stands", "discountPercentage": 20 },
        { "categoryName": "Desks", "discountPercentage": 24 }
      ]
    }
  ]
}

示例 1:更新特定类别的折扣百分比

该示例更新第一个匹配促销活动中“办公桌”类别的折扣百分比。

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

示例 2:更新销售类别总计

该示例使用 <a0/a0> 更新特定类别的总销售额。

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

该查询将“台灯”类别的总销售额增加 1000,将其从 37978 更新为 38978。

{
  "_id": "905d1939-e03a-413e-a9c4-221f74055aac",
  "sales": {
    "salesByCategory": [ { "categoryName": "Desk Lamps", "totalSales": 38978 } ],
    "revenue": 37978
  }
}