运算符 $addToSet
将元素添加到数组(如果它们尚不存在),同时确保集内元素的唯一性。
语法
{
"$addToSet": { <field1>: <value1>, ... }
}
parameters
说明 | |
---|---|
<field1> |
要向其中添加元素的字段。 |
<value1> |
要添加至数组中的值。 |
示例
请查看 StoreData 数据库中 stores 集合的这个示例文档。
{
"_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"
]
}
示例 1:向 tag
数组添加新标签
db.stores.update(
{ "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5" },
{ "$addToSet": { "tag": "#ShopLocal" } }
)
此查询将返回以下文档,因为 #ShopLocal
已经存在。
{
"acknowledged": true,
"insertedId": null,
"matchedCount": "1",
"modifiedCount": "0",
"upsertedCount": 0
}
示例 2:向 promotionEvents
数组添加新的促销活动
仅当 promotionEvents
数组尚不存在时,才向其添加新的促销活动。
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
}