V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
SlipStupig
V2EX  ›  Python

mongodb aggregate 多个值求 sum 怎么破?

  •  
  •   SlipStupig · 2017 年 11 月 23 日 · 4649 次点击
    这是一个创建于 2978 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我的数据结构是这样的:

    {
        "_id": "xxxxxx",
        "detail": {
            "product_name": "swords  big",
            "type": "weapon",
            "make_player": "震荡龙",
            "game_zone": 1
        }
    }
    

    我想统计detail中的数据的多个值的 总和 ,能输出成这样的效果:

    {” game_zone “:1000,  ” type “:200}
    

    怎么写语句可以实现呢?

    9 条回复    2017-11-25 22:27:45 +08:00
    qiuyk
        1
    qiuyk  
       2017 年 11 月 23 日
    直接$match 再$group 不就可以了?
    xlrtx
        2
    xlrtx  
       2017 年 11 月 23 日
    .aggregate([{$match:{}}, {$group:{_id:null, total:{$sum:"$detail.game_zone"}}}])
    SlipStupig
        3
    SlipStupig  
    OP
       2017 年 11 月 23 日
    @qiuyk $sum 求总数只能求一个值
    fordoo
        4
    fordoo  
       2017 年 11 月 24 日
    {$group: {_id: "$detail.type", sum: {$sum: "$detail.game_zone"}}} ?
    SlipStupig
        5
    SlipStupig  
    OP
       2017 年 11 月 24 日
    @fordoo 比如: type: 1 我要得到 sum,game_zone:2 的我要得到一个 sum
    qiuyk
        6
    qiuyk  
       2017 年 11 月 24 日
    @SlipStupig 你这是听谁说的= = 几个值都可以的
    .aggregate([{$match:{}}, {$group:{_id:null, type:{$sum:"$detail.type"}},game_zone:{$sum:"$detail.game_zone"}}}])
    qiuyk
        7
    qiuyk  
       2017 年 11 月 24 日
    括号写错了 不过差不多就是这个意思了
    wx8600
        8
    wx8600  
       2017 年 11 月 25 日
    这不是在文档里面就有的吗……
    SlipStupig
        9
    SlipStupig  
    OP
       2017 年 11 月 25 日
    @wx8600 文档没写统计两个值啊
    关于   ·   帮助文档   ·   自助推广系统   ·   博客   ·   API   ·   FAQ   ·   Solana   ·   3682 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 00:55 · PVG 08:55 · LAX 16:55 · JFK 19:55
    ♥ Do have faith in what you're doing.