 
  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
MongoDB query to set a sub item in an array?
You can use positional $ operator. Let us first create a collection with documents −
> db.demo22.insertOne( ...    { ...       ProductId:101, ... ...       ProductDetails: ...       [ ...          { ...             ProductFirstPrice: '35', ...             ProductSecondPrice: '75' ...          }, ...          { ...             ProductFirstPrice: '', ...             ProductSecondPrice:'' ...          }, ...          { ...             ProductFirstPrice: '78', ...             ProductSecondPrice:'24' ...          } ...       ] ...    } ... ... ); {    "acknowledged" : true,    "insertedId" : ObjectId("5e14c0b422d07d3b95082e70") } Display all documents from a collection with the help of find() method −
> db.demo22.find().pretty();
This will produce the following output −
{    "_id" : ObjectId("5e14c0b422d07d3b95082e70"),    "ProductId" : 101,    "ProductDetails" : [       {          "ProductFirstPrice" : "35",          "ProductSecondPrice" : "75"       },       {          "ProductFirstPrice" : "",          "ProductSecondPrice" : ""       },       {          "ProductFirstPrice" : "78",          "ProductSecondPrice" : "24"       }    ] } Following is the MongoDB query to set a sub item in an array −
> db.demo22.update({ "ProductDetails.ProductFirstPrice" : "35" }, ... { $set : { "ProductDetails.$.ProductFirstPrice" : "" }}, false, true); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) Display all documents from a collection with the help of find() method −
> db.demo22.find().pretty();
This will produce the following output −
{    "_id" : ObjectId("5e14c0b422d07d3b95082e70"),    "ProductId" : 101,    "ProductDetails" : [       {          "ProductFirstPrice" : "",          "ProductSecondPrice" : "75"       },       {          "ProductFirstPrice" : "",          "ProductSecondPrice" : ""       },       {          "ProductFirstPrice" : "78",          "ProductSecondPrice" : "24"       }    ] }Advertisements
 