$addToSet (添加到集合)

运算符 $addToSet 将元素添加到数组(如果它们尚不存在),同时确保集内元素的唯一性。

语法

{
  $addToSet: { <field1>: <value1>, ... }
}

parameters

参数 说明
<field1> 要向其中添加元素的字段。
<value1> 要添加至数组中的值。

例子

请考虑存储集合中的此示例文档。

{
    "_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:向数组添加新标记tag

若要向标记数组添加新标记,请使用 $addToSet 运算符运行查询以添加新值。

db.stores.update({
    "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5"
}, {
    "$addToSet": {
        "tag": "#ShopLocal"
    }
})

此查询返回以下结果:

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

示例 2:向 promotionEvents 数组添加新的促销活动

若要向数组添加新事件 promotionEvents ,请使用$addToSet运算符和要添加的新提升对象运行查询。

db.stores.update({
    "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5"
}, {
    "$addToSet": {
        "promotionEvents": {
            "eventName": "Summer Sale",
            "promotionalDates": {
                "startDate": {
                    "Year": 2024,
                    "Month": 6,
                    "Day": 1
                },
                "endDate": {
                    "Year": 2024,
                    "Month": 6,
                    "Day": 15
                }
            },
            "discounts": [{
                "categoryName": "DJ Speakers",
                "discountPercentage": 20
            }]
        }
    }
})

此查询返回以下结果:

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

示例 3 - 将$addToSet与$setWindowOperators配合使用

若要检索“第一次启动顾问”公司内每个商店的城市列表,请运行对公司第一个分区商店的查询。 然后,使用 $addToSet 运算符为分区中的每个商店添加不同的城市。

db.stores.aggregate([{
    "$match": {
        "company": {
            "$in": ["First Up Consultants"]
        }
    }
}, {
    "$setWindowFields": {
        "partitionBy": "$company",
        "sortBy": {
            "sales.totalSales": -1
        },
        "output": {
            "citiesForCompany": {
                "$push": "$city",
                "window": {
                    "documents": ["unbounded", "current"]
                }
            }
        }
    }
}, {
    "$project": {
        "company": 1,
        "name": 1,
        "citiesForCompany": 1
    }
}])

此查询返回的前两个结果为:

[
    {
        "_id": "a1713bed-4c8b-46e7-bb68-259045dffdb4",
        "name": "First Up Consultants | Bed and Bath Collection - Jaskolskiside",
        "company": "First Up Consultants",
        "citiesForCompany": [
            "South Thelma",
            "South Carmenview",
            "Port Antone",
            "Charlotteville",
            "South Lenorafort",
            "Jaskolskiside"
        ]
    },
    {
        "_id": "6b8585ab-4357-4da7-8625-f6a1cd5796c5",
        "name": "First Up Consultants | Computer Depot - West Zack",
        "company": "First Up Consultants",
        "citiesForCompany": [
            "South Thelma",
            "South Carmenview",
            "Port Antone",
            "Charlotteville",
            "South Lenorafort",
            "Jaskolskiside",
            "West Zack"
        ]
    }
]