title: MongoDB min/max aggregation
body: <p>I've got documents with this simplified schema :</p>
  
  <pre><code>{
     positon: 10,
     value: 5,
     count: 3
  }
  </code></pre>
  
  <p>What I'd like to compute, is to group those documents by <code>position</code> and find the maximum <code>value</code> where the count is greater than 4 but with <code>value</code> less than the minimum <code>value</code> where the count is less than 4.</p>
  
  <p>Here what I've done, but it does not work :</p>
  
  <pre><code>{ $group: { 
            _id: {
                     position: "$position",
                   },
            result: {$max: { $cond: [ {$and: [  {$gte: ["$count", 4]}, 
                                                {$lt: ["$value", {$min: { $cond: [ {$lt: ["$count", 4]}, 
                                                                                   { value: "$value" },  
                                                                                   10]
                                                                        }                                                              
                                                                 }]
                                               }]},
                                      { value: "$value", nb: "$count"}, 
                                      0] 
                          }
                  }
            }
  }
  </code></pre>
  
  <p>I am said that <code>$min</code>is an invalid operator and I cant figure out how to write the right aggregation function. Would it be better to run a mapreduce ?</p>
  
  <p>If for example I have those documents</p>
  
  <pre><code>{Position: 10, value: 1, count 5}
  {Position: 10, value: 3, count 3}
  {Position: 10, value: 4, count 5}
  {Position: 10, value: 7, count 4}
  </code></pre>
  
  <p>I'd like the reslt to be </p>
  
  <pre><code>{Position: 10, value: 1, count 4}
  </code></pre>
  
  <p>As it is the maximum of 'value' where count is greater than 4 but also as there is a value of 3 that has only 3 counts so that the value 4 is not what I'm looking for.</p>