

- 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
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" ] } } }
- Related Questions & Answers
- Add MD5 hash value to MongoDB collection?
- How to add a column in MongoDB collection?
- Sort MongoDB Collection by Array value?
- How to pop a single value in MongoDB?
- Add new field to every document in a MongoDB collection?
- How to update a single field in a capped collection in MongoDB?
- How to get array from a MongoDB collection?
- MongoDB query to add a document in an already created collection
- Make MongoDB replace single array value with string?
- Decrement only a single value in MongoDB?
- MongoDB query to pull array element from a collection?
- How to add a new field to all the documents in a MongoDB collection
- Add field that is unique index to collection in MongoDB?
- How to remove all documents from a collection except a single document in MongoDB?
- How do I add a value to the top of an array in MongoDB?
Advertisements