How do I return a document with filtered sub-documents using Mongo?

MongoDBDatabaseBig Data Analytics

<p>For this, use $project in MongoDB. Within that, use $filter. Let us create a collection with documents &minus;</p><pre class="prettyprint notranslate">&gt; db.demo457.insertOne( ... { ... &nbsp; &nbsp;_id: 101, ... &nbsp; &nbsp;details: [ ... &nbsp; &nbsp; &nbsp; { ProductName:&quot;Product-1&quot; , ProductPrice:90 }, ... &nbsp; &nbsp; &nbsp; { ProductName:&quot;Product-2&quot; , ProductPrice:190 } ... &nbsp; &nbsp;] ... } ... ); { &quot;acknowledged&quot; : true, &quot;insertedId&quot; : 101 } &gt; &gt; db.demo457.insertOne( ... { ... &nbsp; &nbsp;_id: 102, ... &nbsp; &nbsp;details: [ ... &nbsp; &nbsp; &nbsp; { ProductName:&quot;Product-3&quot; , ProductPrice:150}, ... &nbsp; &nbsp; &nbsp; { ProductName:&quot;Product-4&quot; , ProductPrice:360 } ... &nbsp; &nbsp;] ... } ... ); { &quot;acknowledged&quot; : true, &quot;insertedId&quot; : 102 }</pre><p>Display all documents from a collection with the help of find() method &minus;</p><pre class="prettyprint notranslate">&gt; db.demo457.find();</pre><p>This will produce the following output &minus;</p><pre class="result notranslate">{ &quot;_id&quot; : 101, &quot;details&quot; : [ { &quot;ProductName&quot; : &quot;Product-1&quot;, &quot;ProductPrice&quot; : 90 }, { &quot;ProductName&quot; : &quot;Product-2&quot;, &quot;ProductPrice&quot; : 190 } ] } { &quot;_id&quot; : 102, &quot;details&quot; : [ { &quot;ProductName&quot; : &quot;Product-3&quot;, &quot;ProductPrice&quot; : 150 }, { &quot;ProductName&quot; : &quot;Product-4&quot;, &quot;ProductPrice&quot; : 360 } ] }</pre><p>Following is the query to return a document with filtered sub-documents using MongoDB &minus;</p><pre class="prettyprint notranslate" style="">&gt; db.demo457.aggregate([ ... { ... &nbsp; &nbsp;$project: { ... &nbsp; &nbsp; &nbsp; details: { ... &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$filter: { ... &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; input: &quot;$details&quot;, ... &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; as: &quot;output&quot;, ... &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cond: { $gte: [ &quot;$$output.ProductPrice&quot;, 170 ] } ... &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} ... &nbsp; &nbsp; &nbsp; } ... &nbsp; &nbsp;} ... } ... ])</pre><p>This will produce the following output &minus;</p><pre class="result notranslate">{ &quot;_id&quot; : 101, &quot;details&quot; : [ { &quot;ProductName&quot; : &quot;Product-2&quot;, &quot;ProductPrice&quot; : 190 } ] } { &quot;_id&quot; : 102, &quot;details&quot; : [ { &quot;ProductName&quot; : &quot;Product-4&quot;, &quot;ProductPrice&quot; : 360 } ] }</pre>
raja
Updated on 11-May-2020 09:20:20

Advertisements