

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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" ] } ] }
- Related Questions & Answers
- Update an array element matching a condition using $push in MongoDB
- MongoDB query to insert an array element with a condition?
- MongoDB query to update an array using FindAndUpdate()?
- MongoDB query to push document into an array
- How to push an element into array in MongoDB?
- MongoDB query to update all documents matching specific IDs
- MongoDB query to match each element in a documents array to a condition?
- MongoDB query to find matching documents given an array with values?
- How to push an array in MongoDB?
- Update Array element in MongoDB?
- Removing an array element from MongoDB collection using update() and $pull
- Query an array of embedded documents in MongoDB and push another?
- Convert a field to an array using MongoDB update operation?
- Updating an array with $push in MongoDB
- Cannot push into an array from MongoDB?
Advertisements