Perform nested document value search in MongoDB?

MongoDBBig Data AnalyticsDatabase

For searching value, use $match in MongoDB. Let us create a collection with documents −

> db.demo648.insertOne(
...    {
...       StudentInformation:
...       [
...          {
...             Name:"John",
...             CountryName:"US"
...          },
...          {
...             Name:"David",
...             CountryName:"AUS"
...          },
...          {
...             Name:"Chris",
...             CountryName:"US"
...          },
...          {
...             Name:"Robert",
...             CountryName:"UK"
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9c8b286c954c74be91e6f5")
}

Display all documents from a collection with the help of find() method −

> db.demo648.find();

This will produce the following output −

{ "_id" : ObjectId("5e9c8b286c954c74be91e6f5"), "StudentInformation" : [
   { "Name" : "John", "CountryName" : "US" },
   { "Name" : "David", "CountryName" : "AUS" },
   { "Name" : "Chris", "CountryName" : "US" },    
   { "Name" : "Robert", "CountryName" : "UK" } 
] }

Following is the query to search for value in MongoDB −

> db.demo648.aggregate([
...    { $unwind: "$StudentInformation" },
...    { $match: { "StudentInformation.CountryName": "US" } },
...    { $project: {_id: 0}}
... ])

This will produce the following output −

{ "StudentInformation" : { "Name" : "John", "CountryName" : "US" } }
{ "StudentInformation" : { "Name" : "Chris", "CountryName" : "US" } }
raja
Published on 12-May-2020 12:20:12
Advertisements