- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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" }
Advertisements