- 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
How do I push elements to an existing array in MongoDB?
To push elements to an existing array, use $addToSet operator along with update(). Let us first create a collection with documents −
> db.pushElements.insertOne({"Comments":["Good","Awesome","Nice"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd682597924bb85b3f48953") }
Following is the query to display all documents from a collection with the help of find() method −
> db.pushElements.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd682597924bb85b3f48953"), "Comments" : [ "Good", "Awesome", "Nice" ] }
Following is the query to push elements to an existing array in MongoDB −
> db.pushElements.update( {_id:ObjectId("5cd682597924bb85b3f48953")}, { "$addToSet":{"Comments":"Cool"} }, upsert=true ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check the document once again −
> db.pushElements.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd682597924bb85b3f48953"), "Comments" : [ "Good", "Awesome", "Nice", "Cool" ] }
Advertisements