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

MongoDBDatabaseBig Data Analytics

Let us first create a collection with documents −

>db.demo144.insertOne({"EmployeeDetails":[{"EmployeeName":"Chris","EmployeeEmail":"Chris12@gmail.com"},{"EmployeeName":"Bob","EmployeeEmail":"bo22@gmail.com"}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e32f1d8fdf09dd6d08539b9")
}
>db.demo144.insertOne({"EmployeeDetails":[{"EmployeeName":"David","EmployeeEmail":"david@gmail.com"},{"EmployeeName":"Carol","EmployeeEmail":"Carol@gmail.com"}]});
{
   "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" : "Chris12@gmail.com" },
      { "EmployeeName" : "Bob", "EmployeeEmail" : "bo22@gmail.com" }
   ]
}
{
   "_id" : ObjectId("5e32f1f5fdf09dd6d08539ba"), "EmployeeDetails" : [
      { "EmployeeName" : "David", "EmployeeEmail" : "david@gmail.com" },
      { "EmployeeName" : "Carol", "EmployeeEmail" : "Carol@gmail.com" }
   ] 
}

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

>db.demo144.find({"EmployeeDetails.EmployeeName":"David","EmployeeDetails.EmployeeEmail":"david@gmail.com"},{"EmployeeDetails.EmployeeName":1});

This will produce the following output −

{ "_id" : ObjectId("5e32f1f5fdf09dd6d08539ba"), "EmployeeDetails" : [ { "EmployeeName" : "David" }, { "EmployeeName" : "Carol" } ] }
raja
Published on 31-Mar-2020 12:42:46
Advertisements