運算子會將 $add 數字加在一起,或加數字和日期。 新增數字和日期時,數字會解譯為毫秒。
語法
{
$add: [ <listOfExpressions> ]
}
參數
| 參數 | Description |
|---|---|
<listOfExpressions> |
任何解析為數位或日期的有效表達式。 運算式可以是數字和日期的任何組合。 |
範例
請參考商店集合中的此範例檔。
{
"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
"name": "First Up Consultants | Beverage Shop - Satterfieldmouth",
"location": {
"lat": -89.2384,
"lon": -46.4012
},
"staff": {
"totalStaff": {
"fullTime": 8,
"partTime": 20
}
},
"sales": {
"totalSales": 75670,
"salesByCategory": [
{
"categoryName": "Wine Accessories",
"totalSales": 34440
},
{
"categoryName": "Bitters",
"totalSales": 39496
},
{
"categoryName": "Rum",
"totalSales": 1734
}
]
},
"promotionEvents": [
{
"eventName": "Unbeatable Bargain Bash",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 6,
"Day": 23
},
"endDate": {
"Year": 2024,
"Month": 7,
"Day": 2
}
},
"discounts": [
{
"categoryName": "Whiskey",
"discountPercentage": 7
},
{
"categoryName": "Bitters",
"discountPercentage": 15
},
{
"categoryName": "Brandy",
"discountPercentage": 8
},
{
"categoryName": "Sports Drinks",
"discountPercentage": 22
},
{
"categoryName": "Vodka",
"discountPercentage": 19
}
]
},
{
"eventName": "Steal of a Deal Days",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 9,
"Day": 21
},
"endDate": {
"Year": 2024,
"Month": 9,
"Day": 29
}
},
"discounts": [
{
"categoryName": "Organic Wine",
"discountPercentage": 19
},
{
"categoryName": "White Wine",
"discountPercentage": 20
},
{
"categoryName": "Sparkling Wine",
"discountPercentage": 19
},
{
"categoryName": "Whiskey",
"discountPercentage": 17
},
{
"categoryName": "Vodka",
"discountPercentage": 23
}
]
}
]
}
範例 1 - 取得目前和項目人員計數
若要計算員工總數,並預測人員總數,請使用巢狀 totalStaff 物件上的 $add 運算符來傳回所需的結果。
db.stores.aggregate([{
$match: {
_id: "40d6f4d7-50cd-4929-9a07-0a7a133c2e74"
}
}, {
$project: {
name: 1,
currentTotalStaff: {
$add: ["$staff.totalStaff.fullTime", "$staff.totalStaff.partTime"]
},
projectedNextYearStaff: {
$add: ["$staff.totalStaff.fullTime", "$staff.totalStaff.partTime", 2]
}
}
}])
此查詢會傳回下列結果:
[
{
"_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74",
"name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury",
"currentTotalStaff": 39,
"projectedNextYearStaff": 41
}
]