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值
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']} } })
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
Or do calculations in the next pipeline
Solved, it works like this