You can use dot(.) notation to find the document from sub array. Let us first create a collection with documents −
> db.findDocumentDemo.insertOne( ... { ... "EmployeeDetails" : ... { ... "EmployeeAppraisalTime": ... ... [ ... ... {"EmployeeDesignation": "Developer", "Salary": 45000}, ... {"EmployeeDesignation": "Tester", "Salary": 30000}, ... {"EmployeeDesignation": "HR", "Salary": 22000}, ... {"EmployeeDesignation": "Accountant", "Salary": 18000} ... ] ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd2c0f7b64f4b851c3a13a8") } > db.findDocumentDemo.insertOne( ... { ... "EmployeeDetails" : ... { ... "EmployeeAppraisalTime": ... ... [ ... ... {"EmployeeDesignation": "Developer", "Salary": 105000}, ... {"EmployeeDesignation": "Tester", "Salary": 45000}, ... {"EmployeeDesignation": "HR", "Salary": 34000}, ... {"EmployeeDesignation": "Accountant", "Salary": 24000} ... ] ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd2c1d5b64f4b851c3a13a9") }
Following is the query to display all documents from a collection with the help of find() method −
> db.findDocumentDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd2c0f7b64f4b851c3a13a8"), "EmployeeDetails" : { "EmployeeAppraisalTime" : [ { "EmployeeDesignation" : "Developer", "Salary" : 45000 }, { "EmployeeDesignation" : "Tester", "Salary" : 30000 }, { "EmployeeDesignation" : "HR", "Salary" : 22000 }, { "EmployeeDesignation" : "Accountant", "Salary" : 18000 } ] } } { "_id" : ObjectId("5cd2c1d5b64f4b851c3a13a9"), "EmployeeDetails" : { "EmployeeAppraisalTime" : [ { "EmployeeDesignation" : "Developer", "Salary" : 105000 }, { "EmployeeDesignation" : "Tester", "Salary" : 45000 }, { "EmployeeDesignation" : "HR", "Salary" : 34000 }, { "EmployeeDesignation" : "Accountant", "Salary" : 24000 } ] } }
Following is the query to find document from sub array −
> db.findDocumentDemo.find({ 'EmployeeDetails.EmployeeAppraisalTime.EmployeeDesignation': 'Developer', 'EmployeeDetails.EmployeeAppraisalTime.Salary': { '$in': [45000,105000] } } );
This will produce the following output −
{ "_id" : ObjectId("5cd2c0f7b64f4b851c3a13a8"), "EmployeeDetails" : { "EmployeeAppraisalTime" : [ { "EmployeeDesignation" : "Developer", "Salary" : 45000 }, { "EmployeeDesignation" : "Tester", "Salary" : 30000 }, { "EmployeeDesignation" : "HR", "Salary" : 22000 }, { "EmployeeDesignation" : "Accountant", "Salary" : 18000 } ] } } { "_id" : ObjectId("5cd2c1d5b64f4b851c3a13a9"), "EmployeeDetails" : { "EmployeeAppraisalTime" : [ { "EmployeeDesignation" : "Developer", "Salary" : 105000 }, { "EmployeeDesignation" : "Tester", "Salary" : 45000 }, { "EmployeeDesignation" : "HR", "Salary" : 34000 }, { "EmployeeDesignation" : "Accountant", "Salary" : 24000 } ] } }