$each(数组更新)

适用对象: MongoDB vCore

$each 运算符在 $addToSet$push 操作中使用,以便在单个更新操作中向数组字段添加多个元素。 当需要在数组中插入多个项而无需执行多个更新操作时,此运算符非常有用。 $each 运算符可确保将指定数组中的每个项添加至目标数组。

语法

{
  $push: {
    <field>: {
      $each: [ <value1>, <value2>, ... ],
      <modifier1>: <value1>,
      <modifier2>: <value2>,
      ...
    }
  }
}

parameters

说明
<field> 要更新的字段。
$each 要添加至数组字段的值的数组。
<modifier> 可选的修饰符,例如 $sort$slice$position,可控制 $push 操作的行为。

示例

让我们通过以下示例 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
      }
    ],
    "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
        }
      ]
    }
  ],
  "tag": [
    "#ShopLocal",
    "#SeasonalSale",
    "#FreeShipping",
    "#MembershipDeals"
  ]
}

将多个新的促销活动添加至 promotionEvents 数组。

db.stores.updateOne(
  { "name": "Lenore's New DJ Equipment Store" },
  {
    $push: {
      promotionEvents: {
        $each: [
          {
            eventName: "Grand Savings",
            promotionalDates: {
              startDate: "2024-08-01",
              endDate: "2024-08-31"
            },
            discounts: [             
              {
                categoryName: "DJ Headphones",
                discountPercentage: 5
              }
            ]
          },
          {
            eventName: "Big Bargain",
            promotionalDates: {
              startDate: "2024-11-25",
              endDate: "2024-11-30"
            },
            discounts: [
              {
                categoryName: "DJ Headphones",
                discountPercentage: 20
              }
            ]
          }
        ]
      }
    }
  }
)

此查询将返回以下文档。

{
  "acknowledged": true,
  "insertedId": null,
  "matchedCount": "0",
  "modifiedCount": "0",
  "upsertedCount": 0
}