- 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
Cannot push into an array from MongoDB?
To push into an array with MongoDB, use $push. Let us create a collection with documents −
> db.demo445.insertOne({"ListOfFriends":["Robert","Mike","Sam","Carol","David","Mike"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e78f099bbc41e36cc3caec2") }
Display all documents from a collection with the help of find() method −
> db.demo445.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e78f099bbc41e36cc3caec2"), "ListOfFriends" : [ "Robert", "Mike", "Sam", "Carol", "David", "Mike" ] }
Following is the query to push into an array −
> db.demo445.update( ... { _id: ObjectId("5e78f099bbc41e36cc3caec2") }, ... { $push: { ListOfFriends: "Chris Brown" } } ... ) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo445.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e78f099bbc41e36cc3caec2"), "ListOfFriends" : [ "Robert", "Mike", "Sam", "Carol", "David", "Mike", "Chris Brown" ] }
Advertisements