Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
}
]
}Advertisements