 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
 