Removing duplicate keys after $unwind in MongoDB aggregation
<p>Using MongoDB, I'm doing an aggregation pipeline on a document that contains an array called <code>tests</code>, and using an <code>$unwind</code> operation to unwind that array into several documents:</p>

<p>Original document:</p>

<pre><code>{"_id"=&gt;"1867930", "tests"=&gt; [
    {"status"=&gt;"passed", "elapsed_time"=&gt;26, "worker"=&gt;11},
    {"status"=&gt;"passed", "elapsed_time"=&gt;34, "worker"=&gt;13},
    {"status"=&gt;"passed", "elapsed_time"=&gt;23, "worker"=&gt;15}
]}
</code></pre>

<p>Result after <code>$unwind</code>:</p>

<pre><code>{"_id"=&gt;"1867930", "tests"=&gt;{"status"=&gt;"passed", "elapsed_time"=&gt;26, "worker"=&gt;11}}
{"_id"=&gt;"1867930", "tests"=&gt;{"status"=&gt;"passed", "elapsed_time"=&gt;34, "worker"=&gt;13}}
{"_id"=&gt;"1867930", "tests"=&gt;{"status"=&gt;"passed", "elapsed_time"=&gt;23, "worker"=&gt;15}}
</code></pre>

<p>How can I apply another operation to hoist the values of the <code>tests</code> key in each of these documents up a level (i.e. eliminating the duplicate <code>tests</code> keys created from the <code>$unwind</code>) to get the following result?</p>

<pre><code>{"_id"=&gt;"1867930", "status"=&gt;"passed", "elapsed_time"=&gt;26, "worker"=&gt;11}
{"_id"=&gt;"1867930", "status"=&gt;"passed", "elapsed_time"=&gt;34, "worker"=&gt;13}
{"_id"=&gt;"1867930", "status"=&gt;"passed", "elapsed_time"=&gt;23, "worker"=&gt;15}
</code></pre>

<p>Note that this is <em>not</em> renaming the <code>tests</code> key, it's moving the value of <code>tests</code> up a level and merging with the parent hash.</p>