Query MongoDB for a nested search


For nested search, use $and along with $or. Let us first create a collection with documents −

> db.demo12.insertOne({"Name":"Chris","Age":23,"CountryName":"US","Message":"Hello"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e0f70a2d7df943a7cec4fa2")
}
> db.demo12.insertOne({"Name":"David","Age":21,"CountryName":"US","Message":"Hello"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e0f70acd7df943a7cec4fa3")
}
> db.demo12.insertOne({"Name":"Bob","Age":23,"CountryName":"AUS","Message":"Hi"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e0f70bad7df943a7cec4fa4")
}
> db.demo12.insertOne({"Name":"Carol","Age":24,"CountryName":"US","Message":"Hi"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e0f70c7d7df943a7cec4fa5")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.demo12.find();

This will produce the following output −

{ "_id" : ObjectId("5e0f70a2d7df943a7cec4fa2"), "Name" : "Chris", "Age" : 23, "CountryName" : "US", "Message" : "Hello" }
{ "_id" : ObjectId("5e0f70acd7df943a7cec4fa3"), "Name" : "David", "Age" : 21, "CountryName" : "US", "Message" : "Hello" }
{ "_id" : ObjectId("5e0f70bad7df943a7cec4fa4"), "Name" : "Bob", "Age" : 23, "CountryName" : "AUS", "Message" : "Hi" }
{ "_id" : ObjectId("5e0f70c7d7df943a7cec4fa5"), "Name" : "Carol", "Age" : 24, "CountryName" : "US", "Message" : "Hi" }

Here is the query for MongoDB nested search −

> db.demo12.find({ $and : [ { Name : 'Bob' }, { Age : 23 }, { $or : [ { CountryName : 'UK' }, { Message : 'Hi' } ] } ] } );

This will produce the following output −

{ "_id" : ObjectId("5e0f70bad7df943a7cec4fa4"), "Name" : "Bob", "Age" : 23, "CountryName" : "AUS", "Message" : "Hi" }

Updated on: 01-Apr-2020

140 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements