$position(数组更新)

适用对象: MongoDB vCore

$position 运算符用于指定数组中应插入新元素的位置。 当需要在数组的特定索引处插入元素,而不是将其追加到末尾时,此运算符非常有用。

语法

在更新命令中使用 $position 运算符的基本语法如下所示:

{
  "$push": {
    "<arrayField>": {
      "$each": ["<value1>", "<value2>"],
      "$position": <index>
    }
  }
}

参数

说明
<arrayField> 文档中包含要更新的数组的字段。
<value1>, <value2>, ... 要插入到数组中的值。
<index> 应插入值的位置。

示例

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

{
  "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
  "name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile",
  "location": { "lat": 60.1441, "lon": -141.5012 },
  "staff": { "totalStaff": { "fullTime": 2, "partTime": 0 } },
  "sales": {
    "salesByCategory": [
      { "categoryName": "DJ Headphones", "totalSales": 35921 },
      { "categoryName": "DJ Cables", "totalSales": 1000 }
    ],
    "fullSales": 3700
  },
  "promotionEvents": [
    {
      "eventName": "Bargain Blitz Days",
      "promotionalDates": {
        "startDate": { "Year": 2024, "Month": 3, "Day": 11 },
        "endDate": { "Year": 2024, "Month": 2, "Day": 18 }
      },
      "discounts": [
        { "categoryName": "DJ Turntables", "discountPercentage": 18 },
        { "categoryName": "DJ Mixers", "discountPercentage": 15 }
      ]
    },
    {
      "eventName": "Discount Delight Days",
      "promotionalDates": {
        "startDate": { "Year": 2024, "Month": 5, "Day": 11 },
        "endDate": { "Year": 2024, "Month": 5, "Day": 18 }
      }
    }
  ],
  "tag": [
    "#ShopLocal",
    "#FashionStore",
    "#SeasonalSale",
    "#FreeShipping",
    "#MembershipDeals"
  ]
}

示例 1:在数组字段的特定索引位置插入元素

该示例将标签 #NewArrival 插入到特定文档的 tag 数组中的第二个位置(索引 1)。

db.stores.update(
  { "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5" },
  { $push: { "tag": { $each: ["#NewArrival"], $position: 1 } } }
)

示例文档已更新的 tag 字段具有以下值。

{
  "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
  "tag": [
    "#ShopLocal",
    "#NewArrival",
    "#FashionStore",
    "#SeasonalSale",
    "#FreeShipping",
    "#MembershipDeals"
  ]
}