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

MongoDBDatabaseBig Data Analytics

<p>To get the matching document, use $elemMatch. Let us first create a collection with documents &minus;</p><pre class="prettyprint notranslate">&gt; db.getMatchingDocumentDemo.insertOne( &nbsp; &nbsp;{ &nbsp; &nbsp; &nbsp; _id :1, &nbsp; &nbsp; &nbsp; &quot;UserDetails&quot;:[ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;UserName&quot;:&quot;John&quot;, &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;UserAge&quot;:23 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} &nbsp; &nbsp; &nbsp; ] &nbsp; &nbsp;} ); { &quot;acknowledged&quot; : true, &quot;insertedId&quot; : 1 } &gt; db.getMatchingDocumentDemo.insertOne( { _id :2, &quot;UserDetails&quot;:[ { &quot;UserName&quot;:&quot;Larry&quot;, &quot;UserAge&quot;:24 } ] } ); { &quot;acknowledged&quot; : true, &quot;insertedId&quot; : 2 }</pre><p>Following is the query to display all documents from a collection with the help of find() method &minus;</p><pre class="prettyprint notranslate">&gt; db.getMatchingDocumentDemo.find().pretty();</pre><p>This will produce the following output &minus;</p><pre class="prettyprint notranslate">{ &nbsp; &nbsp;&quot;_id&quot; : 1, &nbsp; &nbsp;&quot;UserDetails&quot; : [ &nbsp; &nbsp; &nbsp; { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&quot;UserName&quot; : &quot;John&quot;, &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&quot;UserAge&quot; : 23 &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;] } { &nbsp; &nbsp;&quot;_id&quot; : 2, &nbsp; &nbsp;&quot;UserDetails&quot; : [ &nbsp; &nbsp; &nbsp; { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&quot;UserName&quot; : &quot;Larry&quot;, &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&quot;UserAge&quot; : 24 &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;] }</pre><p>Following is the query to get the matching document inside an array in MongoDB &minus;</p><pre class="prettyprint notranslate">&gt; db.getMatchingDocumentDemo.find({UserDetails: {$elemMatch: {UserAge: 24}}});</pre><p>This will produce the following output &minus;</p><pre class="result notranslate">{ &quot;_id&quot; : 2, &quot;UserDetails&quot; : [ { &quot;UserName&quot; : &quot;Larry&quot;, &quot;UserAge&quot; : 24 } ] }</pre>
raja
Updated on 30-Jul-2019 22:30:26

Advertisements