MongoDB与Pymongo教程

Published at 2021-03-22 10:10

Author:zhangz

View:600


MongoDB

MongoDB是由C语言编写的,是一个基于分布式文件存储的开源数据库系统,MongoDB可以把数据存储为一个文档的形式,而数据结构由键值对(key=>value)组成,MongoDB 文档类似于 JSON 对象,字段值可以包含其他文档,数组及文档数组。

MongoDB基本数据形式示例:

{

​ name: "Mselab",

​ adress: "www.mselab.cn"

​ members:["zhixy","yangll" ,"wangm", "jiangxw", "licj", "zhangz"]

}

安装MongoDB

Windows,Linux,macOS 系统的MongoDB,都可以在MongoDB官网下载。安装流程请参考相应版本的软件文档。

Pymongo

Python 要连接 MongoDB 需要 MongoDB 驱动,使用 PyMongo 驱动来连接。

在Linux系统中运行### python3 -m pip3 install pymongo这行代码,来进行安装pymongo,安装完成后,可以创建一个测试文件,如下图:

import pymongo

如果代码没有报错,则说明安装成功。

创建数据库

import pymongo #导入pymongo模块
client = pymongo.MongoClient('mongodb://localhost:27017/') #建立与mongodb的连接
mydb = client['mselab'] #创建数据库
mycol = mydb['members'] #创建集合

在MongoDB中,只有在数据库中创建集合并插入文档之后,这个数据库才是被创建成功。下面,我们开始创建集合。

当集合被建立起来之后,就需要在集合中进行文档的编写,才能完善数据库。在文档编写中用的最多的操作就是增删改查,下面我们就对这四个方面进行逐一介绍。

数据库操作

(Python Mongodb 插入文档)

在集合中插入文档通常使用insert_one()方法,这种方法的第一参数是字典中的键值对关系。下面我们接着以上图例进行详述。

import pymongo #导入pymongo模块
client = pymongo.MongoClient('mongodb://localhost:27017/') #建立与mongodb的连接
mydb = client['mselab']#创建数据库
mycol = mydb['members'] #创建集合
mylist = {'name':'zhangzhen,'age':'26','gender':'male'}
x = mycol.insert_one(mylist)
print(x)

pymongo.results.InsertOneResults object at 0x104910f88

从以上图例中,我们可以看到结果,insert_one()方法返回InsertOneResult 对象,而该对象中包含 inserted_id 属性,它是插入文档的id 值。在MongoDB中,如果在我们插入文档时没有指定_id,那么MongoDB就会为我们所书写的每一个文档添加一个唯一的id

上述我们使用insert_one()方法,一次插入了一条文档。同理,我们还可以使用insert_many()方法一次性的在集合中插入多条文档,如下图:

import pymongo #导入pymongo模块
client = pymongo.MongoClient('mongodb://localhost:27017/')
mydb = client['mselab']
mycol = mydb['members']
mylist = [
  {'name':'zhangzhen','age':'26','gender':'male'},
  {'name':'licongjian','age':'25','gender':'male'},
  {'name':'wangmin','age':'26','gender':'male'},
]
x = mycol.insert_many(mylist)
print(x.inserted_ids)

在代码的最后一行,我们打印出了每条记录的id,文档的id都是MongoDB为我们添加的。

[ObjectId('6057f5ab12d9a0a579f3fc2f'), ObjectId('6057f5ab12d9a0a579f3fc30'), ObjectId('6057f5ab12d9a0a579f3fc31')]

查 (Python Mongodb 查询文档)

MongoDB 中使用了 find 和 find_one 方法来查询集合中的数据

精确搜索

查询集合中符合条件的文档

import pymongo #导入pymongo模块
client = pymongo.MongoClient('mongodb://localhost:27017/')
mydb = client['mselab']
mycol = mydb['members5']#创建了一个新的集合
mylist = [
  {'name':'zhangzhen','age':'26','gender':'male'},
  {'name':'licongjian','age':'25','gender':'male'},
  {'name':'wangmin','age':'26','gender':'female'},
  {'name':'zhangsan','age':'10','gender':'male'},
  {'name':'lisi','age':'10','gender':'female'}
]
mycol.insert_many(mylist)
for i in mycol.find():
  print(i)

find_one查询第一个符合条件的结果,图例是要查找出第一个年龄为26岁的人员。

import pymongo #导入pymongo模块
client = pymongo.MongoClient('mongodb://localhost:27017/')
mydb = client['mselab']
mycol = mydb['members5']
#mylist = [
#  {'name':'zhangzhen','age':'26','gender':'male'},
# {'name':'licongjian','age':'25','gender':'male'},
# {'name':'wangmin','age':'26','gender':'female'},
# {'name':'zhangsan','age':'10','gender':'male'},
#  {'name':'lisi','age':'10','gender':'female'}
#]
#mycol.insert_many(mylist)
myquery ={'age':'26'}
print(mycol.find_one(myquery))
#for i in mycol.find():
#  print(i)

{'_id': ObjectId('6057f68105718b37311fffc8'), 'name': 'zhangzhen', 'age': '26', 'gender': 'male'}

find查询所有符合条件的结果

import pymongo #导入pymongo模块
client = pymongo.MongoClient('mongodb://localhost:27017/')
mydb = client['mselab']
mycol = mydb['members5']
#mylist = [
#  {'name':'zhangzhen','age':'26','gender':'male'},
# {'name':'licongjian','age':'25','gender':'male'},
# {'name':'wangmin','age':'26','gender':'female'},
# {'name':'zhangsan','age':'10','gender':'male'},
#  {'name':'lisi','age':'10','gender':'female'}
#]
#mycol.insert_many(mylist)
myquery ={'age':'26'} #查询的条件
for i in mycol.find(myquery):
  print(i)

{'_id': ObjectId('6057f68105718b37311fffc8'), 'name': 'zhangzhen', 'age': '26', 'gender': 'male'} {'_id': ObjectId('6057f68105718b37311fffca'), 'name': 'wangmin', 'age': '26', 'gender': 'female'}

查询集合中符合条件文档的指定字段(除了 _id 你不能在一个对象中同时指定 0 和 1,如果你设置了一个字段为 0,则其他都为 1,反之亦然。)

import pymongo #导入pymongo模块
client = pymongo.MongoClient('mongodb://localhost:27017/')
mydb = client['mselab']
mycol = mydb['members5']
#mylist = [
#  {'name':'zhangzhen','age':'26','gender':'male'},
# {'name':'licongjian','age':'25','gender':'male'},
# {'name':'wangmin','age':'26','gender':'female'},
# {'name':'zhangsan','age':'10','gender':'male'},
#  {'name':'lisi','age':'10','gender':'female'}
#]
#mycol.insert_many(mylist)
mystring = {'_id':0,'age':0}#指定不显示的字段
myquery ={'age':'26'}#查询的条件
for i in mycol.find(myquery,mystring):
  print(i)

{'name': 'zhangzhen', 'gender': 'male'} {'name': 'wangmin', 'gender': 'female'}

模糊搜索

查询的条件语句中,我们可以使用修饰符。修饰符还可以指定为正则,图例中,我们是要查找以l开头的名字。

import pymongo #导入pymongo模块
client = pymongo.MongoClient('mongodb://localhost:27017/')
mydb = client['mselab']
mycol = mydb['members5']
#mylist = [
#  {'name':'zhangzhen','age':'26','gender':'male'},
# {'name':'licongjian','age':'25','gender':'male'},
# {'name':'wangmin','age':'26','gender':'female'},
# {'name':'zhangsan','age':'10','gender':'male'},
#  {'name':'lisi','age':'10','gender':'female'}
#]
#mycol.insert_many(mylist)
myquery ={'name':{'!regex':'l'}}#用正则表达式查询以l开头的name,此处感叹号为美元符号
for i in mycol.find(myquery):
  print(i)

{'_id': ObjectId('6057f68105718b37311fffc9'), 'name': 'licongjian', 'age': '25', 'gender': 'male'} {'_id': ObjectId('6057f68105718b37311fffcc'), 'name': 'lisi', 'age': '10', 'gender': 'female'}

limit()返回指定个数的符合条件的结果

import pymongo #导入pymongo模块
client = pymongo.MongoClient('mongodb://localhost:27017/')
mydb = client['mselab']
mycol = mydb['members5']
#mylist = [
#  {'name':'zhangzhen','age':'26','gender':'male'},
# {'name':'licongjian','age':'25','gender':'male'},
# {'name':'wangmin','age':'26','gender':'female'},
# {'name':'zhangsan','age':'10','gender':'male'},
#  {'name':'lisi','age':'10','gender':'female'}
#]
#mycol.insert_many(mylist)
myquery = {'age':{'!gt':'2'}} #此处感叹号为美元符号
for i in mycol.find(myquery).limit(2):
  print(i)

{'_id': ObjectId('6057f68105718b37311fffc8'), 'name': 'zhangzhen', 'age': '26', 'gender': 'male'} {'_id': ObjectId('6057f68105718b37311fffc9'), 'name': 'licongjian', 'age': '25', 'gender': 'male'}

改(Python Mongodb 修改文档)

在 MongoDB 中使用 update_one()update_many()方法修改文档中的记录,该方法第一个参数为查询的条件,第二个参数为要修改的字段。其中,update_one方法如果查找到的匹配数据多于一条,则只会修改第一条。下面进行实例演示:

import pymongo #导入pymongo模块
client = pymongo.MongoClient('mongodb://localhost:27017/')
mydb = client['mselab']
mycol = mydb['members4']
mylist = [
  {'name':'zhangzhen','age':'26','gender':'male'},
  {'name':'licongjian','age':'25','gender':'male'},
  {'name':'wangmin','age':'26','gender':'female'},
  {'name':'zhangsan','age':'10','gender':'male'},            {'name':'lisi','age':'10','gender':'female'}
]
mycol.insert_many(mylist)
#myquery = {'age': '10'}#把age等于10的文档修改为age等于26
#newage = {'!set':{'age':'26'}}#此处感叹号为美元符号
#mycol.update_one(myquery,newage)
for i in mycol.find():
  print(i)

{'_id': ObjectId('6057f8929f5addf9a60e4805'), 'name': 'zhangzhen', 'age': '26', 'gender': 'male'} {'_id': ObjectId('6057f8929f5addf9a60e4806'), 'name': 'licongjian', 'age': '25', 'gender': 'male'} {'_id': ObjectId('6057f8929f5addf9a60e4807'), 'name': 'wangmin', 'age': '26', 'gender': 'female'} {'_id': ObjectId('6057f8929f5addf9a60e4808'), 'name': 'zhangsan', 'age': '10', 'gender': 'male'} {'_id': ObjectId('6057f8929f5addf9a60e4809'), 'name': 'lisi', 'age': '10', 'gender': 'female'}

import pymongo #导入pymongo模块
client = pymongo.MongoClient('mongodb://localhost:27017/')
mydb = client['mselab']
mycol = mydb['members4']
#mylist = [
#  {'name':'zhangzhen','age':'26','gender':'male'},
#  {'name':'licongjian','age':'25','gender':'male'},
#  {'name':'wangmin','age':'26','gender':'female'},
#  {'name':'zhangsan','age':'10','gender':'male'},
#  {'name':'lisi','age':'10','gender':'female'}
#]
#mycol.insert_many(mylist)
myquery = {'age': '10'}#把age等于10的文档修改为age等于26
newage = {'!set':{'age':'26'}}#此处感叹号为美元符号
mycol.update_one(myquery,newage)
for i in mycol.find():
  print(i)

把age等于10的第一个文档修改为age等于26

{'_id': ObjectId('6057f8929f5addf9a60e4805'), 'name': 'zhangzhen', 'age': '26', 'gender': 'male'} {'_id': ObjectId('6057f8929f5addf9a60e4806'), 'name': 'licongjian', 'age': '25', 'gender': 'male'} {'_id': ObjectId('6057f8929f5addf9a60e4807'), 'name': 'wangmin', 'age': '26', 'gender': 'female'} {'_id': ObjectId('6057f8929f5addf9a60e4808'), 'name': 'zhangsan', 'age': '26', 'gender': 'male'} {'_id': ObjectId('6057f8929f5addf9a60e4809'), 'name': 'lisi', 'age': '10', 'gender': 'female'}

import pymongo #导入pymongo模块
client = pymongo.MongoClient('mongodb://localhost:27017/')
mydb = client['mselab']
mycol = mydb['members4']
#mylist = [
#  {'name':'zhangzhen','age':'26','gender':'male'},
#  {'name':'licongjian','age':'25','gender':'male'},
#  {'name':'wangmin','age':'26','gender':'female'},
#  {'name':'zhangsan','age':'10','gender':'male'},         
#  {'name':'lisi','age':'10','gender':'female'}
#]
#mycol.insert_many(mylist)
myquery = {'age': '26'}#把age等于26的文档修改为age等于27
newage = {'!set':{'age':'27'}}#此处感叹号为美元符号
mycol.update_many(myquery,newage)
for i in mycol.find():
  print(i)

以上方法也支持模糊搜索,图例是把所有age等于26的文档修改为age等于27。

{'_id': ObjectId('6057f8929f5addf9a60e4805'), 'name': 'zhangzhen', 'age': '27', 'gender': 'male'} {'_id': ObjectId('6057f8929f5addf9a60e4806'), 'name': 'licongjian', 'age': '25', 'gender': 'male'} {'_id': ObjectId('6057f8929f5addf9a60e4807'), 'name': 'wangmin', 'age': '27', 'gender': 'female'} {'_id': ObjectId('6057f8929f5addf9a60e4808'), 'name': 'zhangsan', 'age': '27', 'gender': 'male'} {'_id': ObjectId('6057f8929f5addf9a60e4809'), 'name': 'lisi', 'age': '10', 'gender': 'female'}

删 (Python Mongodb 删除数据)

上述我们演示了在MongoDB中增添数据,下面我们演示一下在MongoDB中如何删除数据。首先获取一个已经存在的数据库的内容(图片中前三行就是用来获取数据库的)删除数据和增添数据方面有着相似的地方,可以使用 delete_one() 或者delete_many()方法来删除一个文档或多个文档。一般delete_one()是删除第一个符合查询条件的文档。现在我们以删除name字段值为"zhangzhen"的文档为例:

import pymongo #导入pymongo模块
client = pymongo.MongoClient('mongodb://localhost:27017/')
mydb = client['mselab']
mycol = mydb['members']
#mylist = [
#  {'name':'zhangzhen','age':'26','gender':'male'},
#  {'name':'licongjian','age':'25','gender':'male'},
#  {'name':'wangmin','age':'26','gender':'female'},
#  {'name':'zhangsan','age':'10','gender':'male'},         
#  {'name':'lisi','age':'10','gender':'female'}
#]
#mycol.insert_many(mylist)
myquery = {'name': 'zhangzhen'}
mycol.delete_one(myquery)
for i in mycol.find():
  print(i)

{'_id': ObjectId('6057f8929f5addf9a60e4806'), 'name': 'licongjian', 'age': '25', 'gender': 'male'} {'_id': ObjectId('6057f8929f5addf9a60e4807'), 'name': 'wangmin', 'age': '27', 'gender': 'female'} {'_id': ObjectId('6057f8929f5addf9a60e4808'), 'name': 'zhangsan', 'age': '27', 'gender': 'male'} {'_id': ObjectId('6057f8929f5addf9a60e4809'), 'name': 'lisi', 'age': '10', 'gender': 'female'}

name字段值为"zhangzhen"的文档已被删除。

除了支持精确删除外,以上方法还支持模糊删除。如下图:

import pymongo #导入pymongo模块
client = pymongo.MongoClient('mongodb://localhost:27017/')
mydb = client['mselab']
mycol = mydb['members2']
#mylist = [
#  {'name':'zhangzhen','age':'26','gender':'male'},
#  {'name':'licongjian','age':'25','gender':'male'},
#  {'name':'wangmin','age':'26','gender':'female'},
#  {'name':'zhangsan','age':'10','gender':'male'},         
#  {'name':'lisi','age':'10','gender':'female'}
#]
#mycol.insert_many(mylist)
myquery = {'name': {'!regex':'^z'}}#把集合中name以z开头的文档删除,此处感叹号为美元符号
mycol.delete_many(myquery)
for i in mycol.find():
  print(i)

{'_id': ObjectId('6057f8929f5addf9a60e4806'), 'name': 'licongjian', 'age': '25', 'gender': 'male'} {'_id': ObjectId('6057f8929f5addf9a60e4807'), 'name': 'wangmin', 'age': '27', 'gender': 'female'} {'_id': ObjectId('6057f8929f5addf9a60e4809'), 'name': 'lisi', 'age': '10', 'gender': 'female'}

集合中name以z开头的文档已被删除。