How do you convert an array of ObjectIds into an array of embedded documents with a field containing the original array element value?

MongoDBDatabaseBig Data Analytics

<p>For such conversion, use aggregate. Let us create a collection with documents &minus;</p><pre class="prettyprint notranslate">&gt; db.demo343.insertOne({ ... &nbsp; &nbsp;_id: 101, ... &nbsp; &nbsp;UserName: &quot;Chris&quot;, ... &nbsp; &nbsp;details: [ ... &nbsp; &nbsp; &nbsp; {&quot;Name&quot;:&quot;John&quot;}, ... &nbsp; &nbsp; &nbsp; {&quot;Name&quot;:&quot;David&quot;} ... &nbsp; &nbsp;] ... } ... ); { &quot;acknowledged&quot; : true, &quot;insertedId&quot; : 101 }</pre><p>Display all documents from a collection with the help of find() method &minus;</p><pre class="result notranslate">&gt; db.demo343.find().pretty();</pre><p>This will produce the following output &minus;</p><pre class="result notranslate">{ &nbsp; &nbsp;&quot;_id&quot; : 101, &nbsp; &nbsp;&quot;UserName&quot; : &quot;Chris&quot;, &nbsp; &nbsp;&quot;details&quot; : [ &nbsp; &nbsp; &nbsp; { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&quot;Name&quot; : &quot;John&quot; &nbsp; &nbsp; &nbsp; }, &nbsp; &nbsp; &nbsp; { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&quot;Name&quot; : &quot;David&quot; &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;] }</pre><p>Following is the query to convert an array of objects into an array of embedded documents with a field containing the original array element value &minus;</p><pre class="prettyprint notranslate">&gt; db.demo343.aggregate([ ... &nbsp; &nbsp;{ ... &nbsp; &nbsp; &nbsp; $addFields: { ... &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;details: { ... &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $map: { ... &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;input: &quot;$details&quot;, ... &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;in: { Name: &quot;$$this&quot; } ... &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } ... &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} ... &nbsp; &nbsp; &nbsp; } ... &nbsp; &nbsp;}, ... &nbsp; &nbsp; &nbsp; { $out: &quot;demo343&quot; } ... ])</pre><p>Display all documents from a collection with the help of find() method &minus;</p><pre class="result notranslate">&gt; db.demo343.find().pretty();</pre><p>This will produce the following output &minus;</p><pre class="result notranslate" style="">{ &nbsp; &nbsp;&quot;_id&quot; : 101, &nbsp; &nbsp;&quot;UserName&quot; : &quot;Chris&quot;, &nbsp; &nbsp;&quot;details&quot; : [ &nbsp; &nbsp; &nbsp; { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&quot;Name&quot; : { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;Name&quot; : &quot;John&quot; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} &nbsp; &nbsp; &nbsp; }, &nbsp; &nbsp; &nbsp; { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&quot;Name&quot; : { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;Name&quot; : &quot;David&quot; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;] }</pre>
raja
Updated on 02-Apr-2020 07:34:12

Advertisements