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 12:28:56 +08:00 · 3845 次点击
    这是一个创建于 2344 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我的数据结构是这样的:

    {
        "_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 14:36:04 +08:00
    直接$match 再$group 不就可以了?
    xlrtx
        2
    xlrtx  
       2017-11-23 15:23:52 +08:00
    .aggregate([{$match:{}}, {$group:{_id:null, total:{$sum:"$detail.game_zone"}}}])
    SlipStupig
        3
    SlipStupig  
    OP
       2017-11-23 21:39:14 +08:00
    @qiuyk $sum 求总数只能求一个值
    fordoo
        4
    fordoo  
       2017-11-24 09:33:24 +08:00
    {$group: {_id: "$detail.type", sum: {$sum: "$detail.game_zone"}}} ?
    SlipStupig
        5
    SlipStupig  
    OP
       2017-11-24 09:46:02 +08:00
    @fordoo 比如: type: 1 我要得到 sum,game_zone:2 的我要得到一个 sum
    qiuyk
        6
    qiuyk  
       2017-11-24 14:51:26 +08:00
    @SlipStupig 你这是听谁说的= = 几个值都可以的
    .aggregate([{$match:{}}, {$group:{_id:null, type:{$sum:"$detail.type"}},game_zone:{$sum:"$detail.game_zone"}}}])
    qiuyk
        7
    qiuyk  
       2017-11-24 14:53:27 +08:00
    括号写错了 不过差不多就是这个意思了
    wx8600
        8
    wx8600  
       2017-11-25 22:13:45 +08:00
    这不是在文档里面就有的吗……
    SlipStupig
        9
    SlipStupig  
    OP
       2017-11-25 22:27:45 +08:00
    @wx8600 文档没写统计两个值啊
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3392 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 11:15 · PVG 19:15 · LAX 04:15 · JFK 07:15
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.