$subtract(作为算术表达式运算符)

运算符 $subtract 用于减去两个数字并返回结果。 此运算符在各种方案中非常有用,例如计算文档中的日期、时间或数值之间的差异。

语法

{ $subtract: [ <expression1>, <expression2> ] }

参数

参数 说明
<expression1> minuend (要从中减去另一个数字的数字)。
<expression2> 减法(要减去的数字)。

示例

示例 1:从完整销售额中减去总销售额

下面的示例演示如何从fullSales数组中的totalSales值中减去salesByCategory值。

db.collection.aggregate([
  {
    $project: {
      category: "$sales.salesByCategory.categoryName",
      salesDifference: { $subtract: ["$sales.salesByCategory.totalSales", "$sales.fullSales"] }
    }
  }
])

此输出显示每个类别的 totalSales 和 fullSales 之间的差异:

[
  { "_id": 1, "category": "Electronics", "salesDifference": 500 },
  { "_id": 2, "category": "Clothing", "salesDifference": -200 },
  { "_id": 3, "category": "Home Appliances", "salesDifference": 1000 }
]

示例 2:计算促销事件的持续时间

下面的示例通过从中减去startDateendDate来计算促销事件的持续时间(以天为单位)。

db.collection.aggregate([
  {
    $project: {
      eventName: "$promotionEvents.eventName",
      eventDuration: {
        $subtract: [
          { $dateFromParts: { year: "$promotionEvents.promotionalDates.endDate.Year", month: "$promotionEvents.promotionalDates.endDate.Month", day: "$promotionEvents.promotionalDates.endDate.Day" } },
          { $dateFromParts: { year: "$promotionEvents.promotionalDates.startDate.Year", month: "$promotionEvents.promotionalDates.startDate.Month", day: "$promotionEvents.promotionalDates.startDate.Day" } }
        ]
      }
    }
  }
])

此输出计算每个促销事件的开始日期和结束日期之间的天数:

[
  {
    "_id": 4,
    "eventName": "Black Friday",
    "eventDuration": 5
  },
  {
    "_id": 5,
    "eventName": "Holiday Sale",
    "eventDuration": 10
  }
]