- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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" ] }
- Related Articles
- How to push an array in MongoDB?
- How to push an element into array in MongoDB?
- How do I add a field to existing record in MongoDB?
- How do I $set and $push in single update with MongoDB?
- Updating an array with $push in MongoDB
- MongoDB query to push document into an array
- How to push new items to an array inside of an object in MongoDB?
- Cannot push into an array from MongoDB?
- MongoDB $push in nested array?
- How to add items/elements to an existing jagged array in C#?
- How do I add a value to the top of an array in MongoDB?
- How do I recursively remove consecutive duplicate elements from an array?
- How do I remove a string from an array in a MongoDB document?
- How do I remove elements not matching conditions in MongoDB?
- Update an array element matching a condition using $push in MongoDB

Advertisements