title: Mongodb $cond in aggregation framework
body: <p>I have a collection with documents that look like the following:
  {</p>
  
  <pre><code>ipAddr: '1.2.3.4',
  "results" : [
               {
                       "Test" : "Sight",
                       "Score" : "FAIL",
                       "Reason" : "S1002"
               },
               {
                       "Test" : "Speed",
                       "Score" : "FAIL",
                       "Reason" : "85"
               },
               {
                       "Test" : "Sound",
                       "Score" : "FAIL",
                       "Reason" : "A1001"
               }
       ],
       "finalGrade" : "FAILED"
  </code></pre>
  
  <p>}</p>
  
  <p>Here's the aggregation query I'm trying to write, what I want to do (see commented out piece), is to create a grouped field, per ipAddr, of the 
  'Reason / Error' code, but only if the Reason code begins with a specific letter, and only add the code in once, I tried the following:</p>
  
  <pre><code> db.aggregate([
     {$group: 
          {  _id: "$ipAddr", 
           attempts: {$sum:1}, 
           results: {$push: "$finalGrade"},    
          // errorCodes: {$addToSet: {$cond: ["$results.Reason": /[A|B|S|N.*/, "$results.Reason", ""]}},                                                              
          finalResult: {$last: "$finalGrade"} } 
     }
  ]);
  </code></pre>
  
  <p>Everything works, excluding the commented out 'errorCodes' line.  The logic I'm attempting to create is:
  "Add the the errorCodes set the value of the results.Reason code IF it begins with an A, B, S, or N, otherwise there is nothing to add".</p>
  
  <p>For the Record above, the errorCodes set <em>should</em> contain:<br>
    ...
  errorCodes: [S1002,A1001],
    ...</p>