Computer >> Computer tutorials >  >> Programming >> MongoDB

Find result within array of objects and match email address field in MongoDB?


Let us first create a collection with documents −

>db.demo144.insertOne({"EmployeeDetails":[{"EmployeeName":"Chris","EmployeeEmail":"[email protected]"},{"EmployeeName":"Bob","EmployeeEmail":"[email protected]"}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e32f1d8fdf09dd6d08539b9")
}
>db.demo144.insertOne({"EmployeeDetails":[{"EmployeeName":"David","EmployeeEmail":"[email protected]"},{"EmployeeName":"Carol","EmployeeEmail":"[email protected]"}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e32f1f5fdf09dd6d08539ba")
}

Display all documents from a collection with the help of find() method −

> db.demo144.find();

This will produce the following output −

{
   "_id" : ObjectId("5e32f1d8fdf09dd6d08539b9"), "EmployeeDetails" : [
      { "EmployeeName" : "Chris", "EmployeeEmail" : "[email protected]" },
      { "EmployeeName" : "Bob", "EmployeeEmail" : "[email protected]" }
   ]
}
{
   "_id" : ObjectId("5e32f1f5fdf09dd6d08539ba"), "EmployeeDetails" : [
      { "EmployeeName" : "David", "EmployeeEmail" : "[email protected]" },
      { "EmployeeName" : "Carol", "EmployeeEmail" : "[email protected]" }
   ] 
}

Following is the query to find result within array of objects and match email address field −

>db.demo144.find({"EmployeeDetails.EmployeeName":"David","EmployeeDetails.EmployeeEmail":"[email protected]"},{"EmployeeDetails.EmployeeName":1});

This will produce the following output −

{ "_id" : ObjectId("5e32f1f5fdf09dd6d08539ba"), "EmployeeDetails" : [ { "EmployeeName" : "David" }, { "EmployeeName" : "Carol" } ] }