title: Generating Unique Keys when using Aggregation in MongoDB? How to use $out after $unwind?
body: <p><code>db.test.find()</code> provides the following document</p>
  
  <pre><code>/* 1 */
  {
      "_id" : 1,
      "relatives" : [ 
          "A", 
          "B", 
          "C"
      ]
  }
  </code></pre>
  
  <p>after <code>$unwind</code> (<code>db.test.aggregate([{ $unwind : "$relatives"}])</code>) , if becomes </p>
  
  <pre><code>/* 1 */
  {
      "_id" : 1,
      "relatives" : "A"
  }
  
  /* 2 */
  {
      "_id" : 1,
      "relatives" : "B"
  }
  
  /* 3 */
  {
      "_id" : 1,
      "relatives" : "C"
  }
  </code></pre>
  
  <p>Now if I want to <code>$out</code> (<code>db.test.aggregate([{ $unwind : "$relatives"}, {"$out" : "new_collection"}])</code>) the document into another collection, I will get a <strong>duplicate Key error</strong>. There is another question where he/she just wanted to remove the duplicate documents. But as you can see, I will need these different documents. And so, I want to recompute the IDs or create unique IDs for each document so that I can $out the collection successfully. </p>
  
  <p><strong>EDIT 1 :</strong>
  I was able to solve this by using a <strong>ForEach</strong> loop...</p>
  
  <pre><code>count = 1;
  db.test.aggregate([{ $unwind : "$relatives"}]).forEach(function (element){
      element._id = count;
      count++;
      db.new_collection.save(element);
  });
  </code></pre>
  
  <p>...but I want to know if there is a more elegant way to solve this problem.</p>