Use dot notation(.) to search in inner classes using MongoDB. Let us first create a collection with documents −
> db.searchInInnerDemo.insertOne( ... { ... "StudentFirstName" : "Robert", ... "StudentTechnicalDetails": ... { ... "StudentBackEndTechnology" : "MongoDB", ... "StudentLanguage" : "Java" ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd2dd89b64f4b851c3a13d2") } > > db.searchInInnerDemo.insertOne( ... { ... "StudentFirstName" : "David", ... "StudentTechnicalDetails": ... { ... "StudentBackEndTechnology" : "MySQL", ... "StudentLanguage" : "PHP" ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd2dda3b64f4b851c3a13d3") }
Following is the query to display all documents from a collection with the help of find() method −
> db.searchInInnerDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd2dd89b64f4b851c3a13d2"), "StudentFirstName" : "Robert", "StudentTechnicalDetails" : { "StudentBackEndTechnology" : "MongoDB", "StudentLanguage" : "Java" } } { "_id" : ObjectId("5cd2dda3b64f4b851c3a13d3"), "StudentFirstName" : "David", "StudentTechnicalDetails" : { "StudentBackEndTechnology" : "MySQL", "StudentLanguage" : "PHP" } }
Case 1 − Query to search in inner class to match only one property −
>db.searchInInnerDemo.find({"StudentTechnicalDetails.StudentBackEndTechnology":"MongoDB"}).pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd2dd89b64f4b851c3a13d2"), "StudentFirstName" : "Robert", "StudentTechnicalDetails" : { "StudentBackEndTechnology" : "MongoDB", "StudentLanguage" : "Java" } }
Case 2 − Query to search the document with scanning full field name −
>db.searchInInnerDemo.find({"StudentTechnicalDetails":{"StudentBackEndTechnology":"MongoDB","StudentLanguage":"Java"}}).pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd2dd89b64f4b851c3a13d2"), "StudentFirstName" : "Robert", "StudentTechnicalDetails" : { "StudentBackEndTechnology" : "MongoDB", "StudentLanguage" : "Java" } }