
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
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" ] }
Advertisements