title: Mongodb - aggregation $push if conditional
body: <p>I am trying to aggregate a batch of documents. There are two fields in the documents I would like to $push. However, lets say they are "_id" and "A" fields, I only want $push "_id" and "A" if "A" is $gt 0.</p>
  
  <p>I tried two approaches.</p>
  
  <p>First one.</p>
  
  <pre><code>db.collection.aggregate([{
  "$group":{
      "field": {
          "$push": {
              "$cond":[
                  {"$gt":["$A", 0]},
                  {"id": "$_id", "A":"$A"},
                  null
              ]
          }
      },
      "secondField":{"$push":"$B"}
  }])
  </code></pre>
  
  <p>But this will push a null value to "field" and I don't want it.</p>
  
  <p>Second one.</p>
  
  <pre><code>db.collection.aggregate([{
  "$group":
      "field": {
          "$cond":[
              {"$gt",["$A", 0]},
              {"$push": {"id":"$_id", "A":"$A"}},
              null
          ]
      },
      "secondField":{"$push":"$B"}
  }])
  </code></pre>
  
  <p>The second one simply doesn't work...</p>
  
  <p>Is there a way to skip the $push in else case?</p>
  
  <p><strong>ADDED:</strong></p>
  
  <p>Expected documents:</p>
  
  <pre><code>{
      "_id":objectid(1),
      "A":2,
      "B":"One"
  },
  {
      "_id":objectid(2),
      "A":3,
      "B":"Two"
  },
  {
      "_id":objectid(3),
      "B":"Three"
  }
  </code></pre>
  
  <p>Expected Output:</p>
  
  <pre><code>{
      "field":[
          {
              "A":"2",
              "_id":objectid(1)
          },
          {
              "A":"3",
              "_id":objectid(2)
          },
      ],
      "secondField":["One", "Two", "Three"]
  }
  </code></pre>