title: Mongodb Aggregation Rows to Columns
body: <p>I have the following dataset. I need to group them by Account, and then turn the <code>Element_Fieldname</code> into a column.</p>
  
  <pre><code>var collection = [
      {
          Account:12345,
          Element_Fieldname:"cars",
          Element_Value:true
      },
      {
          Account:12345,
          Element_Fieldname:"boats",
          Element_Value:false
      }
  ]
  </code></pre>
  
  <p>This was my attempt to convert rows to columns, but its not working.</p>
  
  <pre><code>db.getCollection('my_collection').aggregate([{
              $match : {
                  Element_Fieldname : {
                      $in : ["cars", "boats"]
                  }
              }
          }, {
              $group : {
                  _id : "$Account",
                  values : {
                      $addToSet : {
                          field : "$Element_Fieldname",
                          value : "$Element_Value"
                      }
                  }
              }
          }, {
              $project : {
                  Account : "$_id",
                  cars : {
                      "$cond" : [{
                              $eq : ["$Element_Fieldname", "cars"]
                          }, "$Element_Value", null]
                  },
                  boats : {
                      "$cond" : [{
                              $eq : ["$Element_Fieldname", "day_before_water_bottles"]
                          }, "$Element_Value", null]
                  },
              }
          }
      ])
  </code></pre>
  
  <p>This just gives me <code>null</code> in my <code>cars</code> and <code>boats</code> fields. Any help would be great.</p>
  
  <p>And this is my desired results:</p>
  
  <pre><code>var desiredResult = [
      {
          Account:12345,
          cars:true,
          boats:false
      }
  ]
  </code></pre>