$pop
The $pop operator in Amazon DocumentDB is used to remove the first or last element from an array field. It is particularly useful when you need to maintain a fixed-size array or implement a queue-like data structure within a document.
Parameters
-
field: The name of the array field to remove an element from. -
value: An integer value that determines the position of the element to remove. A value of1removes the last element, while a value of-1removes the first element.
Example (MongoDB Shell)
This example demonstrates how to use the $pop operator to remove the first and last elements from an array field.
Create sample documents
db.users.insertMany([ { "_id": 1, "name": "John Doe", "hobbies": ["reading", "swimming", "hiking"] }, { "_id": 2, "name": "Jane Smith", "hobbies": ["cooking", "gardening", "painting"] } ])
Query example
// Remove the first element from the "hobbies" array db.users.update({ "_id": 1 }, { $pop: { "hobbies": -1 } }) // Remove the last element from the "hobbies" array db.users.update({ "_id": 2 }, { $pop: { "hobbies": 1 } })
Output
{ "_id" : 1, "name" : "John Doe", "hobbies" : [ "swimming", "hiking" ] }
{ "_id" : 2, "name" : "Jane Smith", "hobbies" : [ "cooking", "gardening" ] }
Code examples
To view a code example for using the $pop command, choose the tab for the language that you want to use: