search

Home  >  Q&A  >  body text

mongodb聚合问题

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值

仅有的幸福仅有的幸福2871 days ago651

reply all(2)I'll reply

  • PHPz

    PHPz2017-05-02 09:21:04

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

    reply
    0
  • 阿神

    阿神2017-05-02 09:21:04

    Solved, it works like this

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

    reply
    0
  • Cancelreply