Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
The $pop
operator in MongoDB is used to remove the first or last element of an array. This operator is useful when you need to manage arrays by removing elements from either end. The $pop
operator can be used in update operations.
{ $pop: { <field>: <value> } }
<field>
: The field that contains the array from which you want to remove an element.<value>
: Use1
to remove the last element, and-1
to remove the first element.
Description | |
---|---|
<field> |
The field that contains the array from which you want to remove an element. |
<value> |
Use 1 to remove the last element, and -1 to remove the first element. |
Let's understand the usage with the following sample 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" },
{ $pop: { "tag": 1 } }
)
This query would return the following document. The last element from the array is removed.
{
"acknowledged": true,
"insertedId": null,
"matchedCount": "1",
"modifiedCount": "1",
"upsertedCount": 0
}
db.stores.update(
{ "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5" },
{ $pop: { "promotionEvents": -1 } }
)
This query would return the following document. The first element from the array is removed.
{
"acknowledged": true,
"insertedId": null,
"matchedCount": "1",
"modifiedCount": "1",
"upsertedCount": 0
}
- Review options for Migrating from MongoDB to Azure Cosmos DB for MongoDB (vCore)
- Read more about Feature compatibility with MongoDB