- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 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" }
- Related Articles
- MongoDB find() query for nested document?
- MongoDB query for ranking / search count?
- Using find() to search for nested keys in MongoDB?
- MongoDB query for specific case insensitive search
- MongoDB query to search for Month and Day only?
- Perform nested document value search in MongoDB?
- MongoDB Query to search for records only in a specific hour?
- Query deeply nested Objects in MongoDB
- MongoDB query to aggregate nested array
- MongoDB query to sort nested array?
- MongoDB query to update nested document
- Write a MongoDB query to get nested value?
- Query a nested field within an array with MongoDB
- Query array of nested string with MongoDB?
- MongoDB query to update the nested document?

Advertisements