 
  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 insert an array element with a condition?
Let us first create a collection with documents −
>db.demo11.insertOne({"ListOfStudent":[{"StudentName":"Chris","ListOfScore":[76,67,54,89]}]}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e0f6e34d7df943a7cec4fa1") } Following is the query to display all documents from a collection with the help of find() method −
> db.demo11.find().pretty();
This will produce the following output −
{    "_id" : ObjectId("5e0f6e34d7df943a7cec4fa1"),    "ListOfStudent" : [       {          "StudentName" : "Chris",          "ListOfScore" : [             76,             67,             54,             89          ]       }    ] } Here is the query to insert an array element with a condition −
> db.demo11.update( {"ListOfStudent.StudentName":"Chris"}, {$push:{"ListOfStudent.$.ListOfScore":98}} ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) Let us check the documents once again −
> db.demo11.find().pretty();
This will produce the following output −
{    "_id" : ObjectId("5e0f6e34d7df943a7cec4fa1"),    "ListOfStudent" : [       {          "StudentName" : "Chris",          "ListOfScore" : [             76,             67,             54,             89,             98          ]       }    ] }Advertisements
 