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
Script to add a single value to array in MongoDB collection?
To add only a single value to array, use $push. Let us first create a collection with documents −
> db.demo3.insertOne(
... {
... "Information" : {
... "Of" : {
... "StudentCode" : "STUDENT101",
... "StudentFavouriteSubject" : [
... "MySQL",
... "Java"
... ]
... }
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e08b7ef25ddae1f53b6221b")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.demo3.find();
This will produce the following output −
{ "_id" : ObjectId("5e08b7ef25ddae1f53b6221b"), "Information" : { "Of" : { "StudentCode" : "STUDENT101", "StudentFavouriteSubject" : [ "MySQL", "Java" ] } } }
Here is the query to add only a single value to array in MongoDB −
> db.demo3.update({},{$push:{"Information.Of.StudentFavouriteSubject":"Spring and Hibernate"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check all the documents once again −
> db.demo3.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5e08b7ef25ddae1f53b6221b"),
"Information" : {
"Of" : {
"StudentCode" : "STUDENT101",
"StudentFavouriteSubject" : [
"MySQL",
"Java",
"Spring and Hibernate"
]
}
}
}Advertisements