- 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 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 Articles
- MongoDB query to push document into an array
- Cannot push into an array from MongoDB?
- How to push an array in MongoDB?
- Update an array element matching a condition using $push in MongoDB
- Push new key element into subdocument of 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?
- Golang Program To Push An Array Into Another Array
- C++ Program to push an array into another array
- How to push an element to the last of an array in TypeScript?
- How to push new items to an array inside of an object in MongoDB?
- How to push an element at the beginning of an array in TypeScript?
- MongoDB $push in nested array?
- How to delete element from an array in MongoDB?

Advertisements