Py学习  »  MongoDB

MongoDB中满足条件的和值

Nilesh Khoriya • 4 年前 • 525 次点击  

当文档中满足某些条件时,我试图得到值的和。 在下面的查询中,我只想在componentId=“ABC”时获取currentValue的和

db.Pointnext_Activities.aggregate( 
{ $project: {        
    _id: 0, 
    componentId:1,
    currentValue:1
        }
},
{ $group: 
    { _id: "$componentId", 
        total: { $sum: "$currentValue" } 
    } 
} 
)
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/52262
 
525 次点击  
文章 [ 1 ]  |  最新文章 4 年前
srinivasy
Reply   •   1 楼
srinivasy    4 年前

请试试这个:

db.Pointnext_Activities.aggregate([{ $match: { componentId: 'ABC' } },
{
    $group:
    {
        _id: "$componentId",
        total: { $sum: "$currentValue" }
    }
}, { $project: { 'componentId': '$_id', total: 1, _id: 0 } }])

如果你只需要总价值&不在乎 成分 要返回,请尝试以下操作:

db.Pointnext_Activities.aggregate([{ $match: { componentId: 'ABC' } },
    {
        $group:
        {
            _id: "",
            total: { $sum: "$currentValue" }
        }
    }, {$project :{total :1, _id:0}}])

如果您总是从过滤器操作(即:; $match ,因为它只保留进一步步骤所需的文档。