zoukankan      html  css  js  c++  java
  • MongoDB 之 aggregate $group 巧妙运用

    有这样一组数据:

    {
        "campaign_id": "A",
        "campaign_name": "A",
        "subscriber_id": "123"
    },
    {
        "campaign_id": "A",
        "campaign_name": "A",
        "subscriber_id": "123"
    },
    {
        "campaign_id": "A",
        "campaign_name": "A",
        "subscriber_id": "456"
    }

      campaign_id 与 campaign_name  分组,并查询出每个分组下的记录条数 及  subscriber_id  不同记录的个数

    关系型数据库SQL示例:

    select campaign_id,campaign_name,count(subscriber_id),count(distinct subscriber_id)
    group by campaign_id,campaign_name from campaigns;

    在MongoDB下就存在两种组合:1) campaign_id, campaign_name, subscriber_id  三个相同的分为一组,

                                                      2) campaign_id, campaign_name  两个相同,subscriber_id 不同分为一组,

    最后通过这两种分组查询出  campaign_id 与 campaign_name  分组,subscriber_id 不同记录的个数

    MongoDB示例:

    db.campaigns.aggregate([
        { "$match": { "subscriber_id": { "$ne": null }}},
    
        // Count all occurrences
        { "$group": {
            "_id": {
                "campaign_id": "$campaign_id",
                "campaign_name": "$campaign_name",
                "subscriber_id": "$subscriber_id"
            },
            "count": { "$sum": 1 }
        }},
    
        // Sum all occurrences and count distinct
        { "$group": {
            "_id": {
                "campaign_id": "$_id.campaign_id",
                "campaign_name": "$_id.campaign_name"
            },
            "totalCount": { "$sum": "$count" },
            "distinctCount": { "$sum": 1 }
        }}
    ])


    文档结果:

    第一个 group:

    { 
        "_id" : { 
            "campaign_id" : "A", 
            "campaign_name" : "A", 
            "subscriber_id" : "456"
        }, 
        "count" : 1 
    }
    { 
        "_id" : { 
            "campaign_id" : "A", 
            "campaign_name" : "A", 
            "subscriber_id" : "123"
        }, 
        "count" : 2
    }

    第二个 group:

    { 
        "_id" : { 
            "campaign_id" : "A", 
            "campaign_name" : "A"
        },
        "totalCount" : 3,
        "distinctCount" : 2
    }

    至此,我们已经查询出一共有 3 条记录,subscriber_id 有两种不同的值

    reference: Mongodb中Aggregation特性


  • 相关阅读:
    2,进程----multiprocessing模块介绍
    1,进程----进程理论知识
    对ORM的理解
    对queryset的理解
    个人总结-10-代码测试整合
    个人总结-9-session的使用,十天免登陆
    个人总结-8-重新写注册和登录界面
    个人总结-7- 实现图片在MySQL数据库中的存储,取出以及显示在jsp页面上
    从人机交互看对搜狗输入法的使用感受
    个人总结6-验证码制作总结
  • 原文地址:https://www.cnblogs.com/molashaonian/p/8569918.html
Copyright © 2011-2022 走看看