 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
Update a specific MongoDB document in array with $set and positional $ operator?
To update a specific document in array with $set and positional $ operator, use MongoDB updateOne(). The updateOne() updates a single document in a collection based on a query filter.
Let us create a collection with documents −
> db.demo462.insertOne( ... { ...    "id":1, ...    "DueDateDetails": [ ...       { ...          "Name": "David", ...          "Age":21, ...          "CountryName":["US","UK"] ...       }, ...       { ... ...          "Name": "Chris", ...          "Age":23, ...          "CountryName":["UK"] ...       } ...    ] ... } ... ); {    "acknowledged" : true,    "insertedId" : ObjectId("5e7f6c59cb66ccba22cc9dce") } Display all documents from a collection with the help of find() method −
> db.demo462.find();
This will produce the following output −
{ "_id" : ObjectId("5e7f6c59cb66ccba22cc9dce"), "id" : 1, "DueDateDetails" : [ { "Name" : "David", "Age" : 21, "CountryName" : [ "US", "UK" ] }, { "Name" : "Chris", "Age" : 23, "CountryName" : [ "UK" ] } ] } Following is the query to update document in array using $set and positional $ operator with updateOne() −
> db.demo462.updateOne( ...    {id: 1, "DueDateDetails.Name": "Chris"}, ...    { $set: { "DueDateDetails.$.CountryName": "AUS"} } ... ) { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 } Display all documents from a collection with the help of find() method −
> db.demo462.find().pretty();
This will produce the following output −
{    "_id" : ObjectId("5e7f6c59cb66ccba22cc9dce"),    "id" : 1,    "DueDateDetails" : [       {          "Name" : "David",          "Age" : 21,          "CountryName" : [             "US",             "UK"          ]       },       {          "Name" : "Chris",          "Age" : 23,          "CountryName" : "AUS"       }    ] }Advertisements
 