- 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
Search a sub-field on MongoDB?
To search a sub-filed in MongoDB, you can use double quotes along with dot notation. Let us first create a collection with documents −
> db.searchSubFieldDemo.insertOne( ... { ... "UserDetails": ... {"UserEmailId":"John123@gmail.com","UserAge":21} ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd3d909edc6604c74817ce2") } > db.searchSubFieldDemo.insertOne( { "UserDetails": {"UserEmailId":"Carol@yahoo.com","UserAge":26} } ); { "acknowledged" : true, "insertedId" : ObjectId("5cd3d9a4edc6604c74817ce3") }
Following is the query to display all documents from a collection with the help of find() method −
> db.searchSubFieldDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd3d909edc6604c74817ce2"), "UserDetails" : { "UserEmailId" : "John123@gmail.com", "UserAge" : 21 } } { "_id" : ObjectId("5cd3d9a4edc6604c74817ce3"), "UserDetails" : { "UserEmailId" : "Carol@yahoo.com", "UserAge" : 26 } }
Following is the query to search a sub-field on MongoDB −
> db.searchSubFieldDemo.find({"UserDetails.UserEmailId":"Carol@yahoo.com"});
This will produce the following output −
{ "_id" : ObjectId("5cd3d9a4edc6604c74817ce3"), "UserDetails" : { "UserEmailId" : "Carol@yahoo.com", "UserAge" : 26 } }
Advertisements
To Continue Learning Please Login
Login with Google