Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Updating an array with $push in MongoDB
To update an array with $push in MongoDB, use the updateOne() method. The $push operator adds elements to an array field, and when combined with the positional operator $, it can target specific array elements.
Syntax
db.collection.updateOne(
{ "arrayField": { "$elemMatch": { "field": "value" } } },
{ "$push": { "arrayField.$.targetField": newElement } }
);
Sample Data
Let us create a collection with documents ?
db.demo526.insertOne({
"CountryName": "US",
"TeacherName": "Bob",
"StudentInformation": [
{
"Name": "Chris",
"Subject": "MySQL",
"ListOfMailId": []
},
{
"Name": "David",
"Subject": "MongoDB",
"ListOfMailId": []
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e8af031437efc8605595b6b")
}
Display all documents from the collection ?
db.demo526.find();
{
"_id": ObjectId("5e8af031437efc8605595b6b"),
"CountryName": "US",
"TeacherName": "Bob",
"StudentInformation": [
{ "Name": "Chris", "Subject": "MySQL", "ListOfMailId": [] },
{ "Name": "David", "Subject": "MongoDB", "ListOfMailId": [] }
]
}
Example: Update Array with $push
Following is the query to update an array with $push ?
db.demo526.updateOne(
{
_id: ObjectId("5e8af031437efc8605595b6b"),
"StudentInformation": { "$elemMatch": { "Name": "David", "Subject": "MongoDB" }}
},
{
"$push": { "StudentInformation.$.ListOfMailId": { "MailId": "David@gmail.com" }}
}
);
{ "acknowledged": true, "matchedCount": 1, "modifiedCount": 1 }
Verify Result
Display the updated document ?
db.demo526.find();
{
"_id": ObjectId("5e8af031437efc8605595b6b"),
"CountryName": "US",
"TeacherName": "Bob",
"StudentInformation": [
{ "Name": "Chris", "Subject": "MySQL", "ListOfMailId": [] },
{ "Name": "David", "Subject": "MongoDB", "ListOfMailId": [{ "MailId": "David@gmail.com" }] }
]
}
Conclusion
The $push operator effectively adds elements to arrays in MongoDB. Combined with $elemMatch and the positional operator $, it enables precise updates to nested array elements within documents.
Advertisements
