![]() |
VOOZH | about |
The $pop operator in MongoDB removes either the first or the last element from an array field during updates, making it useful for maintaining fixed-size arrays such as rolling logs or recent activity lists.
{ $pop: { <field>: <-1 | 1>, ... } }In the following examples, we are working with:
Database: GeeksforGeeks
Collection: logs
Document: Four documents that contain log-related data.
Remove the first element of the recentActions array for the document where user is "Liam" by setting $pop to -1.
db.logs.updateOne(
{ user: "Liam" },
{ $pop: { recentActions: -1 } }
)
Output:
Remove the last element of the recentActions array for the document where user is "Emma" by setting $pop to 1.
db.logs.updateOne(
{ user: "Emma" },
{ $pop: { recentActions: 1 } }
)
Output:
Remove the first element of the activity.history array in the nested document for the user "Olivia" by setting $pop to -1.
db.logs.updateOne(
{ user: "Olivia" },
{ $pop: { "activity.history": -1 } }
)
Output: