我的旧文章,搬运过知乎

  • 前言
  • MongoDB GUI 工具
  • PyMongo(同步)
  • Motor(异步)
  • 后记

前言

最近这几天准备介绍一下 Python 与三大数据库的使用,这是第一篇,首先来介绍 MongoDB 吧,,走起!!

MongoDB GUI 工具

首先介绍一款 MongoDB 的 GUI 工具 Robo 3T,初学 MongoDB 用这个来查看数据真的很爽。可以即时看到数据的增删改查,不用操作命令行来查看。

操作界面图

PyMongo(同步)

可能大家都对 PyMongo 比较熟悉了,这里就简单介绍它的增删改查等操作。

连接

# 普通连接
client = MongoClient('localhost', 27017)
client = MongoClient('mongodb://localhost:27017/')
#
# 密码连接
client = MongoClient('mongodb://username:password@localhost:27017/dbname')
db = client.zfdb
# db = client['zfdb']test = db.test

# 增加一条记录
person = {'name': 'zone','sex':'boy'}
person_id = test.insert_one(person).inserted_id
print(person_id)
# 批量插入
persons = [{'name': 'zone', 'sex': 'boy'}, {'name': 'zone1', 'sex': 'boy1'}]
result = test.insert_many(persons)
print(result.inserted_ids)

# 删除单条记录
result1 = test.delete_one({'name': 'zone'})
pprint.pprint(result1)
# 批量删除
result1 = test.delete_many({'name': 'zone'})
pprint.pprint(result1)

# 更新单条记录
res = test.update_one({'name': 'zone'}, {'$set': {'sex': 'girl girl'}})
print(res.matched_count)
# 更新多条记录
test.update_many({'name': 'zone'}, {'$set': {'sex': 'girl girl'}})

# 查找多条记录
pprint.pprint(test.find())# 添加查找条件
pprint.pprint(test.find({"sex": "boy"}).sort("name"))

聚合

如果你是我的老读者,那么你肯定知道我之前的骚操作,就是用爬虫爬去数据之后,用聚合统计结合可视化图表进行数据展示。

aggs = [{"$match": {"$or" : [{"field1": {"$regex": "regex_str"}}, {"field2": {"$regex": "regex_str"}}]}}, # 正则匹配字段{"$project": {"field3":1, "field4":1}},# 筛选字段 {"$group": {"_id": {"field3": "$field3", "field4":"$field4"}, "count": {"$sum": 1}}}, # 聚合操作
]result = test.aggregate(pipeline=aggs)

例子:以分组的方式统计 sex 这个关键词出现的次数,说白了就是统计有多少个男性,多少个女性。

test.aggregate([{'$group': {'_id': '$sex', 'weight': {'$sum': 1}}}])

聚合效果图:

Python 工作年限要求

Python 学历要求

Motor(异步)

Motor 是一个异步实现的 MongoDB 存储库 Motor 与 Pymongo 的配置基本类似。连接对象就由 MongoClient 变为 AsyncIOMotorClient 了。下面进行详细介绍一下。

连接

# 普通连接
client = motor.motor_asyncio.AsyncIOMotorClient('mongodb://localhost:27017')
# 副本集连接
client = motor.motor_asyncio.AsyncIOMotorClient('mongodb://host1,host2/?replicaSet=my-replicaset-name')
# 密码连接
client = motor.motor_asyncio.AsyncIOMotorClient('mongodb://username:password@localhost:27017/dbname')
# 获取数据库
db = client.zfdb
# db = client['zfdb']
# 获取 collection
collection = db.test
# collection = db['test']

增加一条记录

添加一条记录。

async def do_insert():document = {'name': 'zone','sex':'boy'}result = await db.test_collection.insert_one(document)print('result %s' % repr(result.inserted_id))
loop = asyncio.get_event_loop()
loop.run_until_complete(do_insert())

增加一条记录

批量增加记录

添加结果如图所暗示。

async def do_insert():result = await db.test_collection.insert_many([{'name': i, 'sex': str(i + 2)} for i in range(20)])print('inserted %d docs' % (len(result.inserted_ids),))loop = asyncio.get_event_loop()
loop.run_until_complete(do_insert())

批量增加记录

查找一条记录

async def do_find_one():document = await db.test_collection.find_one({'name': 'zone'})pprint.pprint(document)loop = asyncio.get_event_loop()
loop.run_until_complete(do_find_one())

查找一条记录

查找多条记录

查找记录可以添加筛选条件。

async def do_find():cursor = db.test_collection.find({'name': {'$lt': 5}}).sort('i')for document in await cursor.to_list(length=100):pprint.pprint(document)loop = asyncio.get_event_loop()
loop.run_until_complete(do_find())# 添加筛选条件,排序、跳过、限制返回结果数
async def do_find():cursor = db.test_collection.find({'name': {'$lt': 4}})# Modify the query before iteratingcursor.sort('name', -1).skip(1).limit(2)async for document in cursor:pprint.pprint(document)loop = asyncio.get_event_loop()
loop.run_until_complete(do_find())

查找多条记录

统计

async def do_count():n = await db.test_collection.count_documents({})print('%s documents in collection' % n)n = await db.test_collection.count_documents({'name': {'$gt': 1000}})print('%s documents where i > 1000' % n)loop = asyncio.get_event_loop()
loop.run_until_complete(do_count())

统计

替换

替换则是将除 id 以外的其他内容全部替换掉。

async def do_replace():coll = db.test_collectionold_document = await coll.find_one({'name': 'zone'})print('found document: %s' % pprint.pformat(old_document))_id = old_document['_id']result = await coll.replace_one({'_id': _id}, {'sex': 'hanson boy'})print('replaced %s document' % result.modified_count)new_document = await coll.find_one({'_id': _id})print('document is now %s' % pprint.pformat(new_document))loop = asyncio.get_event_loop()
loop.run_until_complete(do_replace())

替换

更新

更新指定字段,不会影响到其他内容。

async def do_update():coll = db.test_collectionresult = await coll.update_one({'name': 0}, {'$set': {'sex': 'girl'}})print('更新条数: %s ' % result.modified_count)new_document = await coll.find_one({'name': 0})print('更新结果为: %s' % pprint.pformat(new_document))loop = asyncio.get_event_loop()
loop.run_until_complete(do_update())

更新

删除

删除指定记录。

async def do_delete_many():coll = db.test_collectionn = await coll.count_documents({})print('删除前有 %s 条数据' % n)result = await db.test_collection.delete_many({'name': {'$gte': 10}})print('删除后 %s ' % (await coll.count_documents({})))loop = asyncio.get_event_loop()
loop.run_until_complete(do_delete_many())

删除

mongodb添加多条数据_Python 数据库骚操作 -- MongoDB相关推荐

  1. mybatis insert 重复数据2条_Mybatis框架lt;增gt;:添加一条数据到数据库中,insert...

    在以上框架中,前面所搭建好的框架全部固定好,接下来,我们在此基础上实现功能使用insert添加一条数据到数据库中(1)在UserMapper接口中添加对应方法,//在数据库表中增添一条数据,返回为in ...

  2. mongodb添加多条数据_分析了一万多条拼车数据,看看北上广深的各位都回哪过年...

    快过年了,很多同学都踏上了返乡的路.现在交通这么发达,除了高铁飞机外,还可以搭顺风车回家.今天的这篇文章我们就来分析一下拼车数据,看看今年大家都回哪儿过年. 分析了一万多条拼车数据,看看北上广深的各位 ...

  3. python操作hbase如何快速录入多条数据_python 数据库插入多行

    教你如何用python操作数据库mysql ! ! 前言首先,安装需要的环境,Mysql和Python就不说了,必备的东西. 主要是安装的MySQLdb,可以去sf.net下载,具体地址是http:/ ...

  4. mongodb添加多条数据_mongodb一次能插入多少数据

    UYOU insert()方法:下面是在inventory集合中插入一个三个字段的文档:复制代码代码如下:db.inventory.insert( { _id: 10, type: "mis ...

  5. 如何给mysql表添加百万条数据_给mysql一百万条数据的表添加索引

    直接alter table add index 添加索引,执行一个小时没反应,并且会导致锁表:故放弃该办法,最终解决办法如下: 一.打开mysql 命令行客户端 这里我们那可以看到导出的数据文件所存放 ...

  6. MyBatis系列:mybatis用foreach循环添加多条数据!

    MyBatis系列:mybatis用foreach循环添加多条数据! 前言 今天博主将为大家分享MyBatis系列:mybatis用foreach循环添加多条数据!不喜勿喷,如有异议欢迎讨论!欢迎关注 ...

  7. 如果添加1条数据会等待10秒,你愿意等吗

    首先说明,这个问题出于自己写的一个小demo,很简单的数据添加操作,起初就是添加一条数据,成功之后刷新页面.后面觉得,刷新页面体验不好,就改成成功之后异步加载数据了,界面体验好了一些. 但是突然的就在 ...

  8. mysql通过命令添加1条数据

    mysql通过命令添加1条数据 1.语法: INSERT INTO 表名 (字段1,字段2,...字段n) VALUES (值1,值2,...值n); 2.语法解析: INSERT INTO ... ...

  9. 同时更改一条数据_数据库中的引擎、事务、锁、MVCC(二)

    二.事务 介绍锁之前,咱们先介绍一下 什么叫做事务. 事务就是一组对数据库的一系列的操作,要么同时成功,要么同时失败. 1.事务的特性(ACID): 原子性:事务是整个操作,不可分割,要么都成功,要么 ...

最新文章

  1. 阿里AI大牛聂再清重返清华,加入张亚勤AIR战队,说“阿里很支持为国家培养人才”...
  2. Bigtable:一个分布式的结构化数据存储系统(转)
  3. linux 下对u盘分区吗,linux对中毒u盘分区和格式化
  4. word里双横线怎么打_美人计 | 精致打工人秀智,教你内双怎么化
  5. 微软中国:Morro可能将不进入中国市场
  6. UP及按照UP进行软件开发的流程
  7. vxworks系统是用c语言写的吗,VxWorks操作系统基本.doc
  8. 【免费毕设】ASP.NET 城市酒店入住信息管理系统 (源代码+lunwen)
  9. unity2d自动生成敌人_【A*Pathfinding】超级简单的Unity2D寻路
  10. 使用TortoiseGit提交代码到github上
  11. BZOJ 1034: [ZJOI2008]泡泡堂BNB
  12. Windows下的TCP/UDP网络调试工具-NetAssist以及Linux下的nc网络调试工具
  13. 如何制作计算机启动盘,电脑怎么制作U盘启动盘
  14. Windows10系统如何多开微信程序(上班划水必备)
  15. python获取模块的名称_python获取当前模块的名称
  16. C#使用表达式树不能包含动态操作,使用反射的方式来实现T类型
  17. 没想到,还有小白不知道怎么比较数组是否相等以及检出不匹配项
  18. ajax如何实现表单验证码,Ajax实现提交表单时验证码自动验证(原创自Zjmainstay)...
  19. 23考研李林880第九章曲线积分与曲面积分综合题3-21
  20. javaSE_中文转拼音

热门文章

  1. linux权限提升,Linux权限提升
  2. dockerclient 查看端口占用_docker 端口被占用问题解决
  3. android c 对象为空,ndk-jni中C/C++接口函数修改函数参数jobject对象成员值(数组)的有关问题...
  4. 字典的增删改查/元组的创建
  5. hdu 2275 Kiki Little Kiki 1 水题
  6. ubuntu15.10下code::blocks设置运行窗口为gnome命令行
  7. AFNetworking 4.x高版本上传图片,后端采用springBoot测试
  8. IOS 14.5版本之解档和归档的API学习
  9. linux加载内核后如何运行app,Android app启动过程
  10. c++调用gcd函数_c++函数库中一些实用的函数