Definition:
The $push operator is used to add an element to the end of the array.
Syntax:
{ $push: { <field>: <value> } }Examples:
Consider the following document in a collection called students:
{
"_id": 1,
"grades": [44, 78, 38, 80]
}To append 89 to the grades array
db.students.updateOne(
{ _id: 1 },
{ $push: { grades: 89 } }
)The document would look like:
{ "_id": 1, "grades": [ 44, 78, 38, 80, 89 ] }Definition:
The $each is used in conjuction with $push operator to allow multiple elements to be added to the end of the array.
Syntax:
{ $push: { <field>: { $each: [ <value1>, <value2>, ... ] } } }Examples:
Consider the following document in the students collection:
{
"_id": 2,
"name": "Sara",
"grades": [85, 90, 95]
}To append new grades of 80, 88, and 92 to the grades array for the document with _id of 2, we can use the following $push operator with $each operator:
db.students.updateOne(
{ "_id": 2 },
{ $push: { "grades": { $each: [80, 88, 92] } } }
)The final output would be like that:
{
"_id": 2,
"name": "Sara",
"grades": [85, 90, 95, 80, 88, 92]
}Definition:
The $position operator is used to specify the index position at which to insert new elements into an array field using the $push and $each operators.
Syntax:
To insert a single value :
{ $push: { <field>: { $each: [ <value> ], $position: <index> } } }To insert multiple values :
{ $push: { <field>: { $each: [ <value1>, <value2>, ... ], $position: <index> } } }Examples:
Consider the following document in the students collection:
{
"_id": 3,
"name": "Mona",
"grades": [20, 40, 50]
}Consider the following queries:
db.students.updateOne({_id:3}, {$push: {grades: {$each:[10], $position:0}}})
db.students.updateOne({_id:3}, {$push: {grades: {$each:[30], $position:2}}})
db.students.updateOne({_id:3}, {$push:{grades: {$each:[60,70], $position:4}}})-
The
firstquery inserts the value10at position0. Since the original array was[20, 40, 50], the newgradesarray becomes[10, 20, 40, 50]. -
The
secondquery inserts the value30at position2. The current array is[10, 20, 40, 50], so the newgradesarray becomes[10, 20, 30, 40, 50]. -
The
thirdquery inserts the values60and70at position4. The current array is[10, 20, 30, 40, 50], so the newgradesarray becomes[10, 20, 30, 40, 50, 60, 70].
The final document would look like:
{
"_id": 3,
"name": "Mona",
"grades": [10, 20, 30, 40, 50, 60, 70]
}Definition:
The $slice operator is used in update operations to limit the number of elements in an array field after an update.
This is particularly useful when you want to update a document by adding or removing elements from an array while preserving a fixed number of elements in the array.
Similar to the previous $position operator, it must be used in conjuction with $push and $each operators.
Syntax:
{ $slice: <slice> }<slice> is an integer that specifies the number of elements to preserve in the updated array.
The integer can be :
negative: to remove the last n elements from the array.
positive: to limit the array to the first n elements.
Examples:
(1) Consider the following document in the students collection:
{
"_id": 4,
"name": "Ahmed",
"grades": [40, 50, 30, 60, 80]
}The following query trim the array to the first three elements or keep the first three elements.
db.students.update({_id:4}, {$push:{grades: {$each:[], $slice:3}}})The output would be like that:
{
"_id": 4,
"name": "Ahmed",
"grades": [40, 50, 30]
}(2) The following query preserve the last 5 elements in the array after adding 3 new elements.
db.students.updateOne(
{ _id: 5 },
{ $push: { grades: { $each: [80, 90, 95], $slice: -5 } } }
)In the previous query, we add three new grades (80, 90, and 95) to the grades array of the student with _id equal to 5.
The $slice operator with a negative value of -5 specifies that only the latest 5 grades in the array should be preserved, and the remaining grades should be discarded.
For example, if the original grades array for the student was [88 ,90, 70, 55, 64], then the updated grades array after running this update operation would be [55, 64, 80, 90, 95].
(3) The following query preserve the first 3 elements in the array after adding 2 new elements starting from position 0
db.students.updateOne(
{ _id: 6 },
{ $push: { grades: { $each: [80, 90], $position:0, $slice: 3 } } }
)The previous query, Insert 80 and 90 start from position 0 then keep the first three elements.
For example, if the original grades array for the student was [90, 88, 70], then the updated grades array after running this update operation would be [80, 90, 90].
Definition:
the $sort operator can be used in combination with the $push and $each operators to sort the elements in an array field during an update operation.
Syntax:
{ $push: { <field>: { $each: [ <value1>, <value2>, ... ], $sort: <-1 | 1> } } }The $sort operator can be used with two different values as its argument:
1 : for ascending order.
-1: for descending order.
Examples:
Consider the following document in the students collection:
{
"_id": 7,
"name": "Nader",
"grades": [30, 10, 50, 40]
}To insert the values 20 and 70 into the grades array of the document and sort the array in ascending order, you can use the following update operation:
db.student.update(
{ _id: 7 },
{ $push: { grades: { $each: [20, 70], $sort: 1 } } }
)After running the previous operation, the updated document will look like this:
{
"_id": 7,
"name": "Nader",
"grades": [10, 20, 30, 40, 50, 70]
}Definition:
The $addToSet operator adds an element to an array only if it doesn't already exist in the array.
It checks for duplicates and if the element already exists in the array, the operation has no effect.
Use $addToSet operator instead of $push when you want to add a new element to an array field and make sure all elements in the array are unique.
Syntax:
{ $addToSet: { <field>: <value> } }Examples:
Consider the following document in a collection named myCollection:
{
"_id": 1,
"courses": [ "C#", "Python", "Java", "Go" ]
}(1) Adding a unique course:
db.collection.update(
{ _id: 1 },
{ $addToSet: { courses: "JavaScript" } }
)This will add JavaScript to the courses array because it does not already exist.
(2) Adding a non-unique course:
db.collection.update(
{ _id: 1 },
{ $addToSet: { courses: "Java" } }
)This will have no effect on the courses array because Java already exists.
(3) Adding multiple courses with $each:
db.collection.update(
{ _id: 1 },
{ $addToSet: { courses: { $each: ["C", "C++", "C#" ] } } }
)This will add C and C++ because they do not exist in the array, but C# won't be added because it already exists.
Note that the $position, slice and $sort operators cannot be used with $addToSet operator. They are only applicable to the $push operator.
Definition:
The $pull operator is used to remove all occurrences of an element or elements that match a condition from an array.
Syntax:
{ $pull: { <field>: <value|condition> } }Examples:
Consider the following document in a collection named myCollection:
{
"_id": 1,
"items": [4,5,5,6,7,8,9,10]
}(1) To remove all occurance of 5 in items array:
db.myCollection.updateOne({_id:1}, {$pull: {items: 5}});(2) To remove remove 4 and 6 from items field in all docs:
db.myCollection.updateMany({}, {$pull : {items: {$in:[4,6]}}});(3) To remove all elements that are greater than 7:
db.myCollection.update({_id:1}, {$pull: {items: { $gt:7 }}});This final output after applying all the previous queries:
{
"_id": 1,
"items": [7]
}Removing Elements From Array 💥
Definition:
The $pullAll operator is used to remove all occurrences of specified values from an array. It takes an array of values to remove.
Syntax:
{ $pullAll: { <field>: [ <value1>, <value2> ... ]} }Unlike the $pull operator, there is no condition here to apply, we only remove elements that match a set of values.
Examples:
Consider the following document in a collection named myCollection:
{
"_id": 1,
"items": [4,5,5,6,7,8,9,10]
}The following query removes all occurrences of the values 5, 8, 9, and 10 :
db.myCollection.update({_id:1}, {$pullAll: {items: [5,8,9,10] }})The updated document will look like this:
{
"_id": 1,
"items": [4, 6, 7]
}Removing Elements From Array 💥
Definition:
The $pop operator is used to remove the first or last element from the array.
Syntax:
{ $pop: { <field>: <-1 | 1> } }The $pop operator can be used with two different values as its argument:
-1: to remove the first element of the array
1 : to remove the last element of the array.
Examples:
Consider the following document in a collection named myCollection:
{
"_id": 1,
"fruits": [ "apple", "banana", "cherry", "orange" ]
}To remove the first element of fruits array, you can use the following update query:
db.myCollection.updateOne(
{ _id: 1 },
{ $pop: { fruits: -1 } }
)This will result in the following document:
{
"_id": 1,
"fruits": [ "banana", "cherry", "orange" ]
}Similarly, to remove the last element, you can use the following query:
db.myCollection.updateOne(
{ _id: 1 },
{ $pop: { fruits: 1 } }
)This will result in the following document:
{
"_id": 1,
"fruits": [ "banana", "cherry" ]
}Note that the $pop operator only removes one element at a time, and if the array is empty after the element is removed, the entire array will be removed from the document.
Removing Elements From Array 💥
✔️ How To Query Array Fields in MongoDB Documents
✔️ How To Update Array Elements in MongoDB Documents
🕴️ Linkedin: Dragon Slayer 🐲
📝 Articles: All Articles written by D.S
Very helpful. Thank you