1

I have several numeric fields that I need to aggregate. Let's say my document is structured as follows:

_id: 1234,
numValue1: 10,
numValue2: 20,
numValue3: 30,
numValue4: 40

If I wanted to add a computed field to my pipeline using one of the numeric fields, I could do something like this:

db.myCollection.aggregate(
{ 
  $project : {
    someComputedField : { $add:["$numValue1", 15] }
  }
})

If I wanted to add a computed field based on two of these fields, I know I could do something like this:

db.myCollection.aggregate(
{ 
  $project : {
    someComputedField : { $add:["$numValue1", "$numValue2"] }
  }
})

Now, my question is what if I needed to do $numValue1 + $numValue2 + $numValue3 + $numValue4?

Or even more interestingly $numValue1 * ($numValue2 + $numValue3) / $numValue4?

Edenbauer
  • 1,306
  • 1
  • 11
  • 15

2 Answers2

5

$add can accept multiple values, so the first case would be:

someComputedField: {$add: ['$numValue1', '$numValue2', '$numValue3', '$numValue4']}

And you can nest operators, so the second case would be:

someComputedField: {
    $divide: [
        {$multiply: [
            '$numValue1', {$add: ['$numValue2', '$numValue3']}
        ]},
        '$numValue4'
    ]
}
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
-1

Better to use map/reduce when query is not simple add.

db.myCollection.mapReduce(function() {
   emit('result', this.numValue1 * (this.numValue2 + this.numValue3) / this.numValue4);
}, function(key, values) {
   var i=0; values.forEach(function(n){i+=n;}); return i;
});

Also aggregation framework and map/reduce have nearly same performance.

Taha Jahangir
  • 4,774
  • 2
  • 42
  • 49
  • 100% incorrect that aggregation framework and map/reduce have nearly the same performance. Aggregation framework is significantly faster than map/reduce. – Asya Kamsky Dec 16 '12 at 05:11
  • downvoters @Asya , I previously did a test for comparing performance of aggregation framework and map/reduce (with 4million rows, each about 350bytes), and performance was nearly same. I opened a new question in http://stackoverflow.com/q/13908438/326792 , answer on it, and publish your practice. – Taha Jahangir Dec 17 '12 at 05:04
  • your linked question shows a very small dataset used to do grouping by. I don't think you should jump any performance conclusion on the basis on a single test on 200K documents. Btw, I ran your example and got about 5x slower w/MapReduce even with that data. – Asya Kamsky Dec 17 '12 at 10:05