Q:

Min and max values of an array?

I try to calculate a match score of one document compared to the others in my collection. It works with mapReduce, but I wanted to know if this was possible using aggregate (which is said to be 10x faster).
My documents are as follows:
{
name: "John",
age: 27,
track: {
        section: 12, 
        start: 1,
        end: 4
        }
}

The score I try to calculate is simply min(start_track_1, start_track_2) - max(stop_track_1, stop_track_2)
So to calculate John's score, I was trying to create my pipeline, but it fails already at the second operator:
db.test.aggregate(
  { $match: {
    'age' : {$gte: 22, $lte: 34},
    'track.section': 12,
    }
  },
  { $project: { 
        _id : 1,
        name : 1,
        min_end: {$min: ["$track.end", 4]},
        max_start: {$max: ["$track.start", 1]}
     }
  }
)

The shell answers: "errmsg" : "exception: invalid operator '$min'"
The problem is, I though the $min and $max operators worked on an array, just like $add and $subtract...
So now I'm stuck. I think $min and $max used in $group can't help me here...
Any idea ?

A:

$min in aggregation is an operator for $group. 
The conditional operator will give you the minimum-or-default effect. 
You can use the $subtract to do the math in a following pipeline $project. 
Something like:
db.foo.aggregate(
  { $group: { 
        _id : "$name",
        data_min: {$min: "$track.end"},
        data_max: {$max: "$track.start"}
     }
  },
  {
    $project:{
        _id: "$_id",
        score: { $subtract : [ 
            {$cond:[{$gt:["$data_max",1]},"$data_max",1]},
            {$cond:[{$lt:["$data_min",4]},"$data_min",4]}
        ]}
    }
  }
)

