How to get the matching document inside an array in MongoDB?


To get the matching document, use $elemMatch. Let us first create a collection with documents −

> db.getMatchingDocumentDemo.insertOne(
   {
      _id :1,
      "UserDetails":[
         {
            "UserName":"John",
            "UserAge":23
         }
      ]
   }
);
{ "acknowledged" : true, "insertedId" : 1 }
> db.getMatchingDocumentDemo.insertOne( { _id :2, "UserDetails":[ { "UserName":"Larry", "UserAge":24 } ] } );
{ "acknowledged" : true, "insertedId" : 2 }

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

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

This will produce the following output −

{
   "_id" : 1,
   "UserDetails" : [
      {
         "UserName" : "John",
         "UserAge" : 23
      }
   ]
}
{
   "_id" : 2,
   "UserDetails" : [
      {
         "UserName" : "Larry",
         "UserAge" : 24
      }
   ]
}

Following is the query to get the matching document inside an array in MongoDB −

> db.getMatchingDocumentDemo.find({UserDetails: {$elemMatch: {UserAge: 24}}});

This will produce the following output −

{ "_id" : 2, "UserDetails" : [ { "UserName" : "Larry", "UserAge" : 24 } ] }

Updated on: 30-Jul-2019

91 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements