繁体   English   中英

MongoDB Aggregation Framework $ group使用嵌套操作

[英]MongoDB Aggregation Framework $group using nested operations

我有几个数字字段需要聚合。 假设我的文档结构如下:

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

如果我想使用其中一个数字字段向我的管道添加计算字段,我可以这样做:

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

如果我想根据其中两个字段添加一个计算字段,我知道我可以这样做:

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

现在,我的问题是如果我需要做$ numValue1 + $ numValue2 + $ numValue3 + $ numValue4?

或者更有趣的是$ numValue1 *($ numValue2 + $ numValue3)/ $ numValue4?

$add可以接受多个值,因此第一种情况是:

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

你可以嵌套运算符,所以第二种情况是:

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

当查询不简单时,最好使用map / reduce。


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;
});

聚合框架和map / reduce也具有几乎相同的性能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM