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
MongoDB query to update an array element matching a condition using $push?
To update an array element matching a condition using $push in MongoDB, use the positional operator $ to identify the matched array element, then apply $push to add a new field or value to that specific element.
Syntax
db.collection.update(
{"arrayName.field": "matchValue"},
{"$push": {"arrayName.$.newField": "newValue"}}
);
Create Sample Data
Let us first create a collection with documents ?
db.updateArrayElementDemo.insertOne(
{
"UserDetails":
[
{
"UserName":"Chris",
"UserAge":23
}
]
}
);
{
"acknowledged" : true,
"insertedId" : ObjectId("5ce9029378f00858fb12e90d")
}
Display all documents from the collection ?
db.updateArrayElementDemo.find().pretty();
{
"_id" : ObjectId("5ce9029378f00858fb12e90d"),
"UserDetails" : [
{
"UserName" : "Chris",
"UserAge" : 23
}
]
}
Example: Update Array Element Using $push
Update the array element where UserAge is 23 and add a new field using $push ?
db.updateArrayElementDemo.update(
{"UserDetails.UserAge": 23},
{"$push": {"UserDetails.$.UserCountryName": "US"}}
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Verify Result
Check the updated document ?
db.updateArrayElementDemo.find().pretty();
{
"_id" : ObjectId("5ce9029378f00858fb12e90d"),
"UserDetails" : [
{
"UserName" : "Chris",
"UserAge" : 23,
"UserCountryName" : [
"US"
]
}
]
}
Key Points
- The
$positional operator identifies the first array element that matches the query condition. -
$pushcreates a new array field and adds the specified value to it. - If the field already exists as an array,
$pushappends the new value to that array.
Conclusion
Combine the positional operator $ with $push to add new fields or values to specific array elements that match your query condition. This approach ensures precise updates to nested array structures.
Advertisements
