Fetching specific data in MongoDB for better performance


Fetching specific element of object array in MongoDB collection:
For certain conditions we can retrieve only the queried element in an object array in MongoDB collection which will fetch only required data in the API response that will intern improve your application performance. For example there is a collection named “employee”, which has two records given below

Employee collection:



   /* 1 */
 {
  "_id" : ObjectId("5c1b8bd1bc44c0bb3c35a077"),
  "emp_details" : [ 
   {
    "first_name" : "mark",
    "last_name" : "jenkins",
    "department" : "IT"
   }, 
   {
    "name" : "john",
    "last_name" : "gerick",
    "department" : "Technology"
   }
  ]
 }

 /* 2 */
 {
  "_id" : ObjectId("5c1b8bedbc44c0bb3c35a083"),
  "emp_details" : [ 
   {
    "name" : "steve",
    "last_name" : "miller",
    "department" : "OTS"
   }, 
   {
    "name" : "harry",
    "last_name" : "wasnaick",
    "department" : "sales"
   }
  ]
 }



In MongoDB 2.2   
$elemMatch :  Projection operator is used to alter the returned document to contain only the first matched emp_details element :




 db.getCollection('employee').find({"emp_details.first_name": "mark"}, 

           {emp_details: {$elemMatch: {department: "IT"}}}

 )


$ projection  Operator: $ in a projection object field name represents the index of the field's first matching array element from the query. Both will display the same result.




    db.getCollection('employee').find({"emp_details.first_name": "john"}, 

       {_id: 0, 'emp_details.$': 1}

    )


In MongoDB 3.2 :
 $filter aggregation operator will filter an array during projection, its will check for all the element matches in the emp_details object. Below is the example which gives similar result set.





   db.getCollection('employee').aggregate([
    {$match: {'emp_details.first_name': 'john'}},
    {$project: {
        shapes: {$filter: {
            input: '$emp_details',
            as: 'empde',
            cond: {$eq: ['$$empde.first_name', 'john']}
        }},
        _id: 0
    }}
  ])  


Result :



 /* 1 */
 {
  "_id" : ObjectId("5c1ba552bc44c0bb3c35a75d"),
  "emp_details" : [ 
   {
    "first_name" : "mark",
    "last_name" : "jenkins",
    "department" : "IT"
   }
  ]
 }