Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MongoDB query to update an array element matching a condition using $push?
Let us first create a collection with documents −
> db.updateArrayElementDemo.insertOne(
{
"UserDetails":
[
{
"UserName":"Chris",
"UserAge":23
}
]
}
);
{
"acknowledged" : true,
"insertedId" : ObjectId("5ce9029378f00858fb12e90d")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.updateArrayElementDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5ce9029378f00858fb12e90d"),
"UserDetails" : [
{
"UserName" : "Chris",
"UserAge" : 23
}
]
}
Following is the query to update an array element matching a condition using $push −
db.updateArrayElementDemo.update(
{"UserDetails.UserAge": 23},
{"$push": {"UserDetails.$.UserCountryName": "US"}}
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check the document once again −
> db.updateArrayElementDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5ce9029378f00858fb12e90d"),
"UserDetails" : [
{
"UserName" : "Chris",
"UserAge" : 23,
"UserCountryName" : [
"US"
]
}
]
}Advertisements