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
Query an array of embedded documents in MongoDB and push another?
For this, use $push along with update. Let us create a collection with documents −
> db.demo573.insertOne(
... {
... '_id' :101,
... 'SearchInformation' : [
... {
... 'Site' : 'Facebook.com',
... 'NumberOfHits' : 100
... },
... {
... 'Site' : 'Twitter.com',
... 'NumberOfHits' : 300
... }
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : 101 }
Display all documents from a collection with the help of find() method −
> db.demo573.find();
This will produce the following output −
{ "_id" : 101, "SearchInformation" : [ { "Site" : "Facebook.com", "NumberOfHits" : 100 }, { "Site" : "Twitter.com", "NumberOfHits" : 300 } ] }
Following is how to query an array of embedded documents in MongoDB −
> db.demo573.update({
... _id: 101,
... "SearchInformation.Site": {
... $nin: ["Google.com"]
... }
... }, {
... $push: {
... "SearchInformation": {
... 'Site' : 'Google.com',
... 'NumberOfHits' : 10000
... }
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo573.find().pretty();
This will produce the following output −
{
"_id" : 101,
"SearchInformation" : [
{
"Site" : "Facebook.com",
"NumberOfHits" : 100
},
{
"Site" : "Twitter.com",
"NumberOfHits" : 300
},
{
"Site" : "Google.com",
"NumberOfHits" : 10000
}
]
}Advertisements