mongodb聚合问题
仅有的幸福
仅有的幸福 2017-05-02 09:19:04
0
2
627
mongodb里数据结构如下
{'_id': 1, 'a': 10, 'b': 20}

需要得以的结构为
_a: a*2
_b: a*2+b

db.getCollection('XXX').aggregate({
    $project:{
        _a: {$multiply:['$a', 2]},
        _b: {$add:['$this._a', '$b']}
    }
})

我这里怎么使用已经计算好的_a值

仅有的幸福
仅有的幸福

reply all(2)
PHPzhong

You must first understand how aggregation works. If you know Linux, it works very similarly to pipes. The results of one pipeline calculation can be used in the next pipeline. But if you use it in the same pipeline, you can only recalculate it once

db.getCollection('XXX').aggregate({
    $project:{
        _a: {$multiply:['$a', 2]},
        _b: {$add:[{$multiply:['$a', 2]}, '$b']}
    }
});

Or do calculations in the next pipeline

db.getCollection('XXX').aggregate({
    $project: {
        _a: {$multiply:['$a', 2]},
        b: '$b'
    },
    $project: {
        _a: '$_a',
        _b: {$add: ['$_a', '$b']}
});
阿神

Solved, it works like this

db.getCollection('XXX').aggregate({
    $project:{
        _a: {$multiply:['$a', 2]},
        _b: {$add:[{$multiply:['$a', 2]}, '$b']}
    }
})
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template