MongoDB的聚合操作以及与Python的交互

栏目: Python · 发布时间: 7年前

内容简介:上一篇主要介绍了MongoDB的基本操作,包括创建、插入、保存、更新和查询等,链接为MongoDB基本操作。在本文中主要介绍MongoDB的聚合以及与Python的交互。MongoDB中聚合(aggregate)主要用于处理数据(诸如统计平均值,求和等),并返回计算后的数据结果。

上一篇主要介绍了 MongoDB 的基本操作,包括创建、插入、保存、更新和查询等,链接为MongoDB基本操作。

在本文中主要介绍MongoDB的聚合以及与 Python 的交互。

MongoDB聚合

什么是聚合

MongoDB中聚合(aggregate)主要用于处理数据(诸如统计平均值,求和等),并返回计算后的数据结果。

聚合是基于数据处理的聚合管道,每个文档通过由多个阶段组成的管道,可以对每个阶段的管道进行分组、过滤等功能,然后经过一系列处理,输出结果。

语法: db.集合名称.aggregate({管道: {表达式}})

管道一般用于将当前命令的输出结果作为下一个命令的参数。

MongoDB的聚合管道将MongoDB文档在一个管道处理完毕后将结果传递给下一个管道处理。管道操作是可以重复的。

常用管道

下面介绍常用的管道:

$group
$match
$project
$sort
$limit
$skip
$unwind

常用聚合表达式

下面介绍常用的聚合表达式:

  • $sum :计算总和, $sum:1 表示以1计数
  • $avg :计算平均值
  • $min :获取最小值
  • $max :获取最大值
  • $push :在结果文档中插入值到一个数组中
  • $first :根据资源文档的排序,获取第一个文档数据
  • $last :根据资源文档的排序,获取最后一个文档数据

MongoDB聚合实例

现在假设集合 studen 中有以下数据:

{ "_id" : 1, "name" : "小然", "gender" : 1, "age" : 22, "score" : 95 }
{ "_id" : 2, "name" : "小红", "gender" : 0, "age" : 18, "score" : 80 }
{ "_id" : 3, "name" : "小亮", "gender" : 1, "age" : 19, "score" : 60 }
{ "_id" : 4, "name" : "小强", "gender" : 1, "age" : 23, "score" : 70 }
{ "_id" : 5, "name" : "小柔", "gender" : 0, "age" : 20, "score" : 85 }
{ "_id" : 6, "name" : "小雷", "gender" : 1, "age" : 25, "score" : 65 }
{ "_id" : 7, "name" : "小冉", "gender" : 0, "age" : 19, "score" : 70 }
{ "_id" : 8, "name" : "小晴", "gender" : 0, "age" : 18, "score" : 90 }
{ "_id" : 9, "name" : "小齐", "gender" : 1, "age" : 24, "score" : 50 }
  • 以性别进行分组
db.students.aggregate({$group:{_id:"$gender"}})

输出结果为:

MongoDB的聚合操作以及与Python的交互
  • 统计整个文档,获得数据个数和平均分数
db.students.aggregate({$group:{
        _id:null,
        count:{$sum:1},
        avg_score:{$avg:"$score"}
    }})

输出结果为:

MongoDB的聚合操作以及与Python的交互
  • 以性别进行分组,获取不同分组中数据的个数和平均分数
db.students.aggregate({$group:{
        _id:"$gender",
        count:{$sum:1},
        avg_score:{$avg:"$score"}
    }})

输出结果为:

MongoDB的聚合操作以及与Python的交互
  • 使用 $project 修改输出结果
db.students.aggregate(
        {$group:{
            _id:"$gender",
            count:{$sum:1},
            avg_score:{$avg:"$score"}}
        },
        {$project:{
            gender:"$_id",
            count:1,
            _id:0,
            avg_score:"$avg_score"}
        }
    )

输出结果为:

MongoDB的聚合操作以及与Python的交互
  • 使用 $match 选择分数大于等于70的学生,统计男生、女生的人数
db.students.aggregate(
        {$match:{score:{$gte:70}}},
        {$group:{_id:"$gender",count:{$sum:1}}},
        {$project:{gender:"$_id",count:1,_id:0}}
    )

输出结果为:

MongoDB的聚合操作以及与Python的交互

MondoDB与Python的交互

pymongo的安装

使用Python操作MongoDB需要安装 pymongo ,安装方法很简单,使用 pip install pymongo 即可。

实例化并建立连接

首先从 pymongo 中导入 MongoClient ,然后实例化 client ,建立连接,代码如下:

from pymongo import MongoClient
    
    client = MongoClient(host = "127.0.0.1",port = 27017)
        #操作本机MongoDB可以写成client = MongoClient()
    collection = client["test"]["test"]

常用操作实例

  • 插入一条数据
collection.insert_one({"_id":0,"name":"test0"})
  • 插入多条数据
data_list = [{"_id":i,"name":"test{}".format(i)} for i in range(10)]
    collection.insert_many(data_list)
    data_list = [{"name":"test{}".format(i)} for i in range(10)]
    collection.insert_many(data_list)

插入后结果如下图所示, 下面的操作都在此数据库上进行操作。

MongoDB的聚合操作以及与Python的交互

  • 查询一条记录
print(collection.find_one({"name":"test2"}))

输出结果为:

MongoDB的聚合操作以及与Python的交互
  • 查询所有记录
result = collection.find({"name":"test2"})
    for i in result:
        print(i)

输出结果为:

MongoDB的聚合操作以及与Python的交互
  • 更新一条数据
collection.update_one({"name":"test1"},{"$set":{"name":"test10"}})

执行完操作后,数据库如下图所示:

MongoDB的聚合操作以及与Python的交互
  • 更新全部数据
collection.update_many({"name":"test2"},{"$set":{"name":"test20"}})

执行完操作后,数据库如下图所示:

MongoDB的聚合操作以及与Python的交互
  • 删除一条数据
collection.delete_one({"name":"test3"})

执行完操作后,数据库如下图所示:

MongoDB的聚合操作以及与Python的交互
  • 删除所有满足条件的数据
collection.delete_many({"name":"test4"})

执行完操作后,数据库如下图所示:

MongoDB的聚合操作以及与Python的交互

结语

  • 本篇主要介绍了MongoDB的聚合操作以及与Python的交互,但对于我目前的学习阶段来说,只用到了Python中的插入数据语句,其他的操作基本没有用到。
  • 感谢大家的阅读,有错误希望大家能够指出,我会积极改正。

以上所述就是小编给大家介绍的《MongoDB的聚合操作以及与Python的交互》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Pro Git

Pro Git

Scott Chacon / Apress / 2009-8-27 / USD 34.99

Git is the version control system developed by Linus Torvalds for Linux kernel development. It took the open source world by storm since its inception in 2005, and is used by small development shops a......一起来看看 《Pro Git》 这本书的介绍吧!

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

html转js在线工具
html转js在线工具

html转js在线工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具