- Trending Categories
- 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
MongoDB query to push document into an array
To push document into an array, use $push along with update(). Let us create a collection with documents −
>db.demo310.insertOne({"Name":"Chris","details":[{"Id":101,"Subject":"MySQL"},{"Id":102,"Subject":"MongoDB"}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e50cabdf8647eb59e562043") }
Display all documents from a collection with the help of find() method −
> db.demo310.find();
This will produce the following output −
{ "_id" : ObjectId("5e50cabdf8647eb59e562043"), "Name" : "Chris", "details" : [ { "Id" : 101, "Subject" : "MySQL" }, { "Id" : 102, "Subject" : "MongoDB" } ] }
Following is the query to push document −
> db.demo310.update({ _id:ObjectId("5e50cabdf8647eb59e562043")}, ...{ $push: {"details": { ... "Id" : 103, ... "Subject": "Java" ... }} ...} ...) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo310.find();
This will produce the following output −
{ "_id" : ObjectId("5e50cabdf8647eb59e562043"), "Name" : "Chris", "details" : [ { "Id" : 101, "Subject" : "MySQL" }, { "Id" : 102, "Subject" : "MongoDB" }, { "Id" : 103, "Subject" : "Java" } ] }
Advertisements