社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  MongoDB

MongoDB中满足条件的和值

Nilesh Khoriya • 5 年前 • 652 次点击  

当文档中满足某些条件时,我试图得到值的和。 在下面的查询中,我只想在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
 
652 次点击  
文章 [ 1 ]  |  最新文章 5 年前
srinivasy
Reply   •   1 楼
srinivasy    5 年前

请试试这个:

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 ,因为它只保留进一步步骤所需的文档。