title: mongodb query and return specific elements in array of documents, return some result even if null
body: <p>suppose i have these documents in a collection:</p>
  
  <pre><code> {_id: 1,fruit: apple,attributes: [{color: red,size: small,qty: 5},{color: green,size: small, qty 3}]},
   {_id: 2,fruit: mango,attributes: [{color: red,size: big, qty: 6},{color: green,size: small, qty: 7},{color: gold,size: medium, qty: 5},{color: yellow,size: small, qty: 20}]},
   {_id: 3,fruit: pineapple },
   {_id: 4,fruit: orange,attributes: [{color: orange,size: small,qty: 2}]}
  </code></pre>
  
  <ul>
  <li>all documents will always have the field "fruit" </li>
  <li>some documents may    not have the "attributes" array</li>
  <li>for documents which have elements in attributes array, it can be
  between 1 and 20 elements</li>
  </ul>
  
  <p>i need to return this based on attributes.qty between 4 and 8</p>
  
  <ul>
  <li>always show id and fruit even if attributes field is missing or the qty criteria is not matched</li>
  <li><p>show only a max of 2 elements in the attributes array which match search criteria, sorted in descending order of qty</p>
  
  <p>{_id: 1,fruit: apple,attributes: [{color: red,size: small,qty: 5}]},</p>
  
  <p>{_id: 2,fruit: mango,attributes: [{color: green,size: small, qty: 7}, {color: red,size: big, qty: 6}]},</p>
  
  <p>{_id: 3,fruit: pineapple },</p>
  
  <p>{_id: 4,fruit: orange }</p></li>
  </ul>
  
  <p>this is the query i am using:</p>
  
  <pre><code>db.test.aggregate([
  {"$unwind":"$attributes"},
  {"$match":{"attributes.qty": {$gt:4, $lt:8}}},
  {"$group":{"_id":"$_id","fruit":{$first:"$fruit"},"attributes":{$addToSet: "$attributes"}}}
  ])
  </code></pre>
  
  <p>I am getting the following result:</p>
  
  <pre><code> {_id: 1,fruit: apple,attributes: [{color: red,size: small,qty: 5}]},
   {_id: 2,fruit: mango,attributes: [{color: red,size: big, qty: 6},{color: green,size: small, qty: 7},{color: gold,size: medium, qty: 5}]}
  </code></pre>
  
  <p>This does not have pineapple and orange records; values in attributes for mango are not sorted and not limited to 2</p>
  
  <p>Please help</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>Tried using $redact. still not close to getting desired output. on using $and, there is no output</p>
  
  <pre><code>db.test.aggregate([
  {$match:{"site":{$exists:true}}},
          { "$redact": {
          "$cond": {
              "if": {
                  $and:[ 
                  {"$gt": ["$qty",4]},
                  {"$lt": ["$qty,8]}
                  ]
              },
              "then": "$$DESCEND",
              "else": "$$PRUNE"
          }
      }}
  ])
  </code></pre>