- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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