Array Update Operators in MongoDB
MongoDB’s array update operators are essential for modifying data in document arrays. These operators make adding, removing, and updating items easy and efficient, sometimes with criteria or orders.

An description of the array update operators you have requested is provided below:
Let’s use a collection named blogPosts with the following sample data:
db.blogPosts.insertMany([
{
"_id": 1,
"title": "Introduction to MongoDB",
"author": "Alice",
"tags": ["database", "nosql", "mongodb", "beginners"],
"comments": [
{ "user": "Bob", "text": "Great post!", "date": ISODate("2024-01-10T10:00:00Z") },
{ "user": "Charlie", "text": "Very helpful.", "date": ISODate("2024-01-11T11:00:00Z") }
],
"ratings": [5, 4, 5]
},
{
"_id": 2,
"title": "Advanced JavaScript Features",
"author": "David",
"tags": ["javascript", "web", "frontend", "advanced"],
"comments": [
{ "user": "Eve", "text": "Good read.", "date": ISODate("2024-02-01T14:00:00Z") }
],
"ratings": [4, 4]
},
{
"_id": 3,
"title": "Python for Data Science",
"author": "Frank",
"tags": ["python", "data science"],
"comments": [],
"ratings": [5]
}
]);
$push Operator
An array can have a value appended to the end using the $push operator. Should the designated field be empty, $push will generate a new array containing the value. You can add values to an array of any acceptable BSON type. An error message will appear if the field is present but not an array.
Because they may modify the document’s size and require a disc rewrite, $push changes are slower.
Syntax:
{ $push: { <field1>: <value1>, <field2>: <value2>, ... } }
Code example:
Add a new tag “update-operators” to the “Introduction to MongoDB” post:
db.blogPosts.updateOne(
{ "title": "Introduction to MongoDB" },
{ $push: { "tags": "update-operators" } }
);
Add a new comment to “Advanced JavaScript Features”:
db.blogPosts.updateOne(
{ "title": "Advanced JavaScript Features" },
{
$push: {
"comments": { "user": "Grace", "text": "Very informative.", "date": ISODate() }
}
}
);
$addToSet Operator
Only if the value does not already exist in the array does the $addToSet operator add it. This guarantees unique array elements. Not all array elements are ordered.
Syntax:
{ $addToSet: { <field1>: <value1>, ... } }
Code example:
Add “security” tag to “Introduction to MongoDB” (if not already present):
db.blogPosts.updateOne(
{ "title": "Introduction to MongoDB" },
{ $addToSet: { "tags": "security" } }
);
Attempt to add “mongodb” tag to “Introduction to MongoDB” again:
db.blogPosts.updateOne(
{ "title": "Introduction to MongoDB" },
{ $addToSet: { "tags": "mongodb" } }
);
$each Modifier
Modifier $each in MongoDB Together with $push and $addToSet, $each adds several values to an array.
Syntax (used with $push):
{ $push: { <field>: { $each: [ <value1>, <value2>, ... ] } } }
Code example:
Add multiple new tags to “Advanced JavaScript Features”:
db.blogPosts.updateOne(
{ "title": "Advanced JavaScript Features" },
{ $push: { "tags": { $each: ["express", "node.js", "backend"] } } }
);
$slice Modifier
When used with $push and $each, the $slice modifier which was first introduced in MongoDB v2.4 limits the size of an array. Following the pushing of elements, it essentially truncates the array to a predetermined size. When $slice is set to a positive value (supported since MongoDB 2.6), the first n elements are retained, whereas the last n elements are retained.
It’s crucial to distinguish this modifier from the $slice projection operator, which returns a subset of array elements in find() searches.
Syntax:
{ $push: { <field>: { $each: [ <value1>, ... ], $slice: <numericValue> } } }
Code example:
Add a new rating to “Python for Data Science” and keep only the last 3 ratings:
db.blogPosts.updateOne(
{ "title": "Python for Data Science" },
{
$push: {
"ratings": {
$each: [6], // Add a new rating
$slice: -3 // Keep only the last 3 elements
}
}
}
);
Add new comments to “Introduction to MongoDB” and keep only the first 2 comments:
db.blogPosts.updateOne(
{ "title": "Introduction to MongoDB" },
{
$push: {
"comments": {
$each: [
{ "user": "Newbie", "text": "First comment", "date": ISODate("2024-07-01T00:00:00Z") },
{ "user": "Oldie", "text": "Second comment", "date": ISODate("2024-07-02T00:00:00Z") }
],
$slice: 2 // Keep only the first 2 elements
}
}
}
);
$sort Modifier
Modifier for $sort in MongoDB Together with $push, $each, and $slice, the $sort modifier was also introduced in MongoDB v2.4 and is used to arrange subdocuments inside an array in a certain order prior to slicing. This is very helpful for keeping “top N” lists or other ordered lists of a set size.
Syntax:
{ $push: { <field>: { $each: [ <value1>, ... ], $sort: { <sortField>: <1 | -1> } } } }
Code example:
Add new ratings to “Advanced JavaScript Features” and keep the ratings array sorted in ascending order:
db.blogPosts.updateOne(
{ "title": "Advanced JavaScript Features" },
{
$push: {
"ratings": {
$each: [5, 2],
$sort: 1 // Sort numerically ascending
}
}
}
);
Add a new comment and sort comments by date (ascending) for “Python for Data Science”:
db.blogPosts.updateOne(
{ "title": "Python for Data Science" },
{
$push: {
"comments": {
$each: [
{ "user": "Henry", "text": "Great insights!", "date": ISODate("2024-05-15T09:00:00Z") },
{ "user": "Ivy", "text": "Very useful.", "date": ISODate("2024-05-14T10:00:00Z") }
],
$sort: { "date": 1 } // Sort by date ascending
}
}
}
);
$pop Operator
One element can be taken out of the beginning or end of an array with the $pop operator. A value of 1 eliminates the last element, while a value of -1 eliminates the initial element.
$pop does not return the value that was removed, in contrast to standard stack operations.
Syntax:
{ $pop: { <field>: <1 | -1> } }
Code example:
Remove the last rating from the “Introduction to MongoDB” post:
db.blogPosts.updateOne(
{ "title": "Introduction to MongoDB" },
{ $pop: { "ratings": 1 } } // Remove from end
);
Remove the first tag from the “Python for Data Science” post:
db.blogPosts.updateOne(
{ "title": "Python for Data Science" },
{ $pop: { "tags": -1 } } // Remove from beginning
);
$pull Operator
All instances of a particular value or values that satisfy a provided query criterion are eliminated from an array using the $pull operator. The element can be removed without knowing its location.
Notably, $pull eliminates not only the first matching element but all of them.
Syntax:
{ $pull: { <field1>: <value|condition>, <field2>: <value|condition>, ... } }
Code example:
Remove the tag “beginners” from the tags array of the “Introduction to MongoDB” post:
db.blogPosts.updateOne(
{ "title": "Introduction to MongoDB" },
{ $pull: { "tags": "beginners" } }
);
Remove all comments made by “Bob” from the “Introduction to MongoDB” post:
db.blogPosts.updateOne(
{ "title": "Introduction to MongoDB" },
{ $pull: { "comments": { "user": "Bob" } } }
);
$pullAll Operator
Multiple specified values can be removed from an array in a single operation with the $pullAll operator. The removal process requires a range of values.
Syntax:
{ $pullAll: { <field1>: [ <value1>, <value2>, ... ], ... } }
Code example:
Remove “database” and “nosql” tags from the “Introduction to MongoDB” post:
db.blogPosts.updateOne(
{ "title": "Introduction to MongoDB" },
{ $pullAll: { "tags": ["database", "nosql"] } }
);
Positional Operator ($)
Positional Operator ($) for MongoDB To update a single element in an array that satisfies the query criteria, use the positional operator ($) without knowing the element’s precise index. For the index of the first matched element, it serves as a stand-in. Only the first matching document is updated when this operator is used with update().
Syntax:
{ "arrayField.$": <value> } // For setting a value
{ "arrayField.$.<subField>": <value> } // For setting a subfield
Code example:
Find the comment by “Eve” in “Advanced JavaScript Features” and update its text:
db.blogPosts.updateOne(
{
"title": "Advanced JavaScript Features",
"comments.user": "Eve" // Query to find the document AND the array element
},
{
$set: { "comments.$.text": "This post is truly insightful!" } // $ refers to the matched comment's index
}
);
Update the first rating of “Python for Data Science” to 4:
db.blogPosts.updateOne(
{ "title": "Python for Data Science", "ratings": 5 }, // Find the post and an element with value 5
{ $set: { "ratings.$": 4 } } // Update the first element that matched 5
);
All Positional Operator ($[])
($[]) MongoDB All Positional Operator arrayFilters, which were introduced in MongoDB 3.6, let you change multiple elements in an array that meet certain criteria when you use an identifier like $[]. This is a more sophisticated type of positional update that has the ability to impact several array items.
Syntax:
{ "arrayField.$[]": <value> } // For setting a value
{ "arrayField.$[].<subField>": <value> } // For setting a subfield
Code example:
Set a read status to true for all comments in “Introduction to MongoDB”:
db.blogPosts.updateOne(
{ "_id": 1 },
{ $set: { "comments.$[].read": true } }
);
$position Modifier
Modifier for $position in MongoDB The $push operator in the $position modifier as a new modifier that it supports. However, neither thorough examples nor more justification for its use. Its function is to indicate where in the array to add elements, as opposed to $push’s default behaviour of adding to the end.
Syntax:
{ $push: { <field>: { $each: [ <value1>, <value2>, ... ], $position: <index> } } }
Code example:
Add a new tag “new-concept” to the beginning of the tags array for “Introduction to MongoDB”:
db.blogPosts.updateOne(
{ "title": "Introduction to MongoDB" },
{
$push: {
"tags": {
$each: ["new-concept"],
$position: 0
}
}
}
);
Insert a rating of 3 at index 1 for “Advanced JavaScript Features”:
db.blogPosts.updateOne(
{ "title": "Advanced JavaScript Features" },
{
$push: {
"ratings": {
$each: [3],
$position: 1
}
}
}
);