$slice(数组更新)

适用对象: MongoDB vCore

$slice 运算符用于限制查询中返回的数组的元素数量。 在处理只需要元素子集的大型数组时,它非常有用。 此运算符可以应用于数组,以返回前 N 个元素、后 N 个元素或特定的元素范围。

语法

$slice 运算符的常规语法如下所示:

{
  "$push": {
    "<field>": {
      "$each": [ "<value1>", "<value2>" ],
      "$slice": <num>
    }
  }
}

参数

说明
field $slice 运算符应用到的数组字段。
<value1>, <value2> 要插入到数组中的值。 我们可以保留一个空数组,以通过数组字段中的现有值进行切片。
<num> 如果值为零,则清空数组;如果为负值,则保留数组末尾的多个元素;如果为正值,则保留数组开头的多个元素。

示例

让我们通过 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": "Discount Delight Days",
      "promotionalDates": {
        "startDate": { "Year": 2024, "Month": 5, "Day": 11 },
        "endDate": { "Year": 2024, "Month": 5, "Day": 18 }
      }
    },
    {
      "eventName": "New Promotion Event",
      "promotionalDates": {
        "startDate": { "Year": 2024, "Month": 7, "Day": 1 },
        "endDate": { "Year": 2024, "Month": 7, "Day": 7 }
        },
        "discounts": [
          { "categoryName": "DJ Lights", "discountPercentage": 20 }
        ]
    },
    {
        "eventName": "Cyber Monday Event",
        "promotionalDates": {
          "startDate": { "Year": 2024, "Month": 8, "Day": 1 },
          "endDate": { "Year": 2024, "Month": 8, "Day": 7 }
        },
        "discounts": [ { "categoryName": "DJ Speakers", "discountPercentage": 25 } ]
    }
  ],
  "tag": [
    "#ShopLocal",
    "#NewArrival",
    "#FashionStore",
    "#SeasonalSale",
    "#FreeShipping",
    "#MembershipDeals"
  ]
}

示例 1:数组字段的前 N 个或后 N 个元素的切片

该示例使用 $push$eachpromotionEvents 数组和 $slice 添加新元素,以仅保留前 N 个(正切片)或后 N 个(负切片)元素。 这种方式确保数组在更新后保留最新的条目。

db.stores.updateOne(
  { _id: '7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5' },
  {
    $push: {
      promotionEvents: {
        $each: [
          {
            eventName: "Black Friday Event",
            promotionalDates: {
              startDate: { Year: 2024, Month: 8, Day: 1 },
              endDate: { Year: 2024, Month: 8, Day: 7 }
            },
            discounts: [
              { categoryName: 'DJ Speakers', discountPercentage: 25 }
            ]
          },
          {
            eventName: "Mega Discount Days",
            promotionalDates: {
              startDate: { Year: 2024, Month: 5, Day: 11 },
              endDate: { Year: 2024, Month: 5, Day: 18 }
            },
            discounts: [
              { categoryName: "DJ Lights", discountPercentage: 20 }
            ]
          }
        ],
        $slice: -3
      }
    }
  }
)

该查询将 Black Friday EventMega Discount Days 事件添加至 promotionEvents 数组,并为数组中的后 3 个元素添加切片。

{
  "_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": "Cyber Monday Event",
      "promotionalDates": {
        "startDate": { "Year": 2024, "Month": 8, "Day": 1 },
        "endDate": { "Year": 2024, "Month": 8, "Day": 7 }
      },
      "discounts": [
        { "categoryName": "DJ Speakers", "discountPercentage": 25 }
      ]
    },
    {
      "eventName": "Black Friday Event",
      "promotionalDates": {
        "startDate": { "Year": 2024, "Month": 8, "Day": 1 },
        "endDate": { "Year": 2024, "Month": 8, "Day": 7 }
      },
      "discounts": [
        { "categoryName": "DJ Speakers", "discountPercentage": 25 }
      ]
    },
    {
      "eventName": "Mega Discount Days",
      "promotionalDates": {
        "startDate": { "Year": 2024, "Month": 5, "Day": 11 },
        "endDate": { "Year": 2024, "Month": 5, "Day": 18 }
      },
      "discounts": [
        { "categoryName": "DJ Lights", "discountPercentage": 20 }
      ]
    }
  ],
  "tag": [
    "#ShopLocal",
    "#NewArrival",
    "#FashionStore",
    "#SeasonalSale",
    "#FreeShipping",
    "#MembershipDeals"
  ]
}