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
      }
   ]
}

Updated on: 15-May-2020

94 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements