Tutorialspoint

1 Answer
Nishtha Thakur

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 } ] }

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.