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: 2020-05-15T05:45:05+05:30

195 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements