zoukankan      html  css  js  c++  java
  • MongoDB 数据库 — 实例总结

    本篇打算总结一些碰到的实例,后面碰到问题再进行补充。

    实例1:aggregate 实现 count(distinct field)

    我们知道在 SQL 中,要实现这样的功能,只需要 count(distinct field) 即可,虽然 MongoDB 中有聚合函数 count,distinct,但是,在 aggregate 聚合管道操作中却没有这样的用法,因此,需要使用其它方法来实现这种功能。

    1 聚合函数 count 和 distinct

    # count 聚合函数
    db.collection.count(<query>)
    
    #或者
    db.collection.find(<query>).count()
    
    # distinct 聚合函数
    db.collection.distinct(field, query)
    
    # 例如
    db.collection.distinct('user', {'age': {'$gt': 28}});  //用于查询年龄age大于28岁的不同用户名
    

    2 aggregate 管道操作中实现 count(distinct field) 功能

    对集合中每个 account 使用的不同 vendor 个数计数

    # 文档内容
    {
        { _id: 1,
         account: 'abc',
         vendor: 'amazon'
        },
    
        { _id: 2,
         account: 'abc',
         vendor: 'overstock'
        },
    
        { _id: 3,
         account: 'adf',
         vendor: 'amazon'
        }
    }
    
    # 统计方法
    db.collection.aggregate([
                    { '$group': { '_id': { 'account': '$account', 'vendor': '$vendor'} },
                      'number': { '$sum': 1 }                                        
                    },
                    { '$group': { '_id': '$_id.account' },
                      'number': { '$sum': 1 }
                    }
        ])
    
    # 结果
    [ 
        { '_id': 'abc', 'number': 2 },
        { '_id': 'adf', 'number': 1 }
    ]
    

    参考资料

    MongoDB Aggregation: Counting distinct fields

  • 相关阅读:
    爬虫 效率
    Scrapy 数据存储 图片和文件
    装饰器
    Django 项目部署测试
    Django 项目部署
    Django JS
    三十九、管理信息系统 第三部分 作业
    三十八、模型分离(选做)
    三十七、密码保护
    三十六、实现搜索功能
  • 原文地址:https://www.cnblogs.com/shaocf/p/11098720.html
Copyright © 2011-2022 走看看