

- 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 add new array element in document
To add new array element in a MongoDB document, use $(projection) along with update(). Let us create a collection with documents −
>db.demo222.insertOne({"details":[{"StudentName":"Chris","StudentMarks":78},{"StudentName":"David","StudentMarks":89}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e3ee31703d395bdc213472f") }
Display all documents from a collection with the help of find() method −
> db.demo222.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e3ee31703d395bdc213472f"), "details" : [ { "StudentName" : "Chris", "StudentMarks" : 78 }, { "StudentName" : "David", "StudentMarks" : 89 } ] }
Following is the query to add new array element in document −
> db.demo222.update({"details.StudentName" : "Chris"},{"$set" : {"details.$.SubjectName":"MongoDB"}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo222.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e3ee31703d395bdc213472f"), "details" : [ { "StudentName" : "Chris", "StudentMarks" : 78, "SubjectName" : "MongoDB" }, { "StudentName" : "David", "StudentMarks" : 89 } ] }
- Related Questions & Answers
- Add new field to every document in a MongoDB collection?
- How to add a sub-document to sub-document array in MongoDB?
- MongoDB query to push document into an array
- MongoDB query to add a document in an already created collection
- Include all existing fields and add new fields to document in MongoDB?
- MongoDB query to remove array elements from a document?
- MongoDB query to update nested document
- How to add new item in nested array with MongoDB?
- Filter query on array of embedded document with MongoDB?
- Add a field to an embedded document in an array in MongoDB?
- MongoDB query to return only embedded document?
- MongoDB query to get last inserted document?
- MongoDB query to remove a specific document
- MongoDB query to remove subdocument from document?
- MongoDB query to update the nested document?
Advertisements