$pull
运算符用于从数组中删除与条件匹配的指定值或值的所有实例。 当需要清理或修改文档中的数组数据时,这非常有用。
{ $pull: { <field>: <value|condition> } }
说明 | |
---|---|
<field> |
要从其中删除一个或多个值的字段。 |
<value|condition> |
要从数组中删除的值或条件。 |
让我们通过以下示例 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
}
],
"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"
]
}
db.stores.update(
{ _id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5" },
{ $pull: { tag: "#SeasonalSale" } }
)
此查询将返回以下文档。
{
"acknowledged": true,
"insertedId": null,
"matchedCount": "1",
"modifiedCount": "1",
"upsertedCount": 0
}
db.stores.update(
{ _id: "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5" },
{ $pull: { promotionEvents: { "promotionalDates.endDate.Year": 2024, "promotionalDates.endDate.Month": { $lt: 3 } } } }
)
此查询将返回以下文档。
{
"acknowledged": true,
"insertedId": null,
"matchedCount": "1",
"modifiedCount": "1",
"upsertedCount": 0
}
如果标准 Mongo 命令没有限制/偏差,则删除,否则根据需要进行更新。