Search for documents matching first item in an array with MongoDB?


Let us first create a collection with documents −

> db.matchingFirstItemInTheArrayDemo.insertOne(
   {
      "ClientDetails": [
         {
            "ClientName": "Larry",
            "ClientAge":28
         }
      ]
   }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7a5d26d78f205348bc636")
}
> db.matchingFirstItemInTheArrayDemo.insertOne(
{
   "ClientDetails": [
      {
         "ClientName": "Chris",
         "ClientAge":56,
      }
   ]
}
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7a5f56d78f205348bc637")
}
> db.matchingFirstItemInTheArrayDemo.insertOne(
   {
      "ClientDetails": [
         {
            "ClientName": "Robert",
            "ClientAge":46,
         }
      ]
   }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7a6076d78f205348bc638")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.matchingFirstItemInTheArrayDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cd7a5d26d78f205348bc636"),
   "ClientDetails" : [
      {
         "ClientName" : "Larry",
         "ClientAge" : 28
      }
   ]
}
{
   "_id" : ObjectId("5cd7a5f56d78f205348bc637"),
   "ClientDetails" : [
      {
         "ClientName" : "Chris",
         "ClientAge" : 56
      }
   ]
}
{
   "_id" : ObjectId("5cd7a6076d78f205348bc638"),
   "ClientDetails" : [
      {
         "ClientName" : "Robert",
         "ClientAge" : 46
      }
   ]
}

Following is the query to search for documents matching first item in array −

> db.matchingFirstItemInTheArrayDemo.find({"ClientDetails.0.ClientName":"Chris"});

This will produce the following output −

{ "_id" : ObjectId("5cd7a5f56d78f205348bc637"), "ClientDetails" : [ { "ClientName" : "Chris", "ClientAge" : 56 } ] }

Updated on: 30-Jul-2019

74 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements