

- 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
How to push an element into array in MongoDB?
To push an element into array, use $push. Let us first create a collection with documents −
> db.demo6.insertOne({"ListOfNames":["Bob","David","Mike","Sam"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e0b6b3f25ddae1f53b62228") }
Following is the query to display all documents from a collection with the help of find() method −
> db.demo6.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e0b6b3f25ddae1f53b62228"), "ListOfNames" : [ "Bob", "David", "Mike", "Sam" ] }
Here is the query to push an element into array in MongoDB −
> db.demo6.update({ _id: ObjectId("5e0b6b3f25ddae1f53b62228") },{ $push: { ListOfNames: "Robert" } }); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Following is the query to display all documents from a collection with the help of find() method −
> db.demo6.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e0b6b3f25ddae1f53b62228"), "ListOfNames" : [ "Bob", "David", "Mike", "Sam", "Robert" ] }
- Related Questions & Answers
- Cannot push into an array from MongoDB?
- MongoDB query to push document into an array
- How to push an array in MongoDB?
- Push new key element into subdocument of MongoDB?
- Update an array element matching a condition using $push in MongoDB
- MongoDB query to update an array element matching a condition using $push?
- Updating an array with $push in MongoDB
- How do I push elements to an existing array in MongoDB?
- MongoDB $push in nested array?
- How to push new items to an array inside of an object in MongoDB?
- Push query results into variable with MongoDB?
- How to delete element from an array in MongoDB?
- Implement MongoDB $push in embedded document array?
- Query an array of embedded documents in MongoDB and push another?
- How to remove an array element by its index in MongoDB?
Advertisements