驱动模块
- pymongo是python里常用的操作MongoDB的驱动模块
- 可用pip下载安装
pip install pymongo
创建连接
- MongoClient是MongoDB的客户端代理对象,可以用来执行增删改查操作,而且还内置了连接池
from pymongo import MongoClient
client = MongoClient(host="localhost",port=27017)
client.admin.authenticate("admin","123456")
数据写入
- insert_one和insert_many两个函数可向MongoDB写入数据
client.school.student.insert_one({"name":"alex"})
client.school.student.insert_many({"name":"bob"},{"name":"cindy"})
数据查询
- find_one和find两个函数可从MmongDB中查询数据
student = client.school.student.find_one({"name":"alex"})
print(student)
students = client.school.student.find({})
for one in students:
print(one["_id"],one["name"])
- skip:用于数据分类查询
- limit:用于数据分页查询
students = client.school.student.find({}).skip(0).limit(10)
- count_documents:查询记录总数
count = client.school.student.count_documents({})
- distinct:查询不重复的字段
students = client.school.student.distinct("name")
- sort:对查询结果进行排序
students = client.school.student.find().sort([("name",-1)])
数据修改
- update_one和update_many两个函数可以修改MongoDB数据
client.school.student.update_one({"name":"alex"},{"$set":{"sex":"女"}})
client.school.student.update_many({},{"$set":{"grade":"七年级"}})
数据删除
- delete_one和delete_many两个函数可以删除MongoDB数据
client.school.student.delete_one({"name":"alex"})
client.school.student.delete_many({})
存储文件
连接GridFS
- GridFS是MongoDB的文件存储方案,主要用于存储超过16M的文件
from gridfs import GridFS
db = client.school
gfs = GridFS(db,collection="book")
保存文件
- put函数可把文件保存到GridFS中
file = open("D:/Python编程:从入门到实践.pdf","rb")
args = {"type":"PDF","keyword":"Python"}
gfs.put(file,file="Python编程:从入门到实践.PDF",**args)
file.close()
查找文件
- find_one和find函数可以查找GridFS中存储的文件
book = gfs.find_one({"filename":"Python编程:从入门到实践.PDF"})
print(book.keywode)
books = gfs.find({"type":"PDF"})
for one in books:
print(one.filename)
判断是否存储了文件
- exists可判断GridFS是否存储了某个文件
rs = gfs.exists({"filename":"Python编程:从入门到实践.PDF"})
print(rs)
读取文件
- get函数可以从GfridFS中读取文件,并且只能通过主键读取
from bson.objectid import ObjectId
book = gfs.find_one({"filename":"Python编程:从入门到实践.PDF"})
id = book._id
document = gfs.get(ObjectId(id))
file = open("D:/Python从入门到实践.PDF","wb")
file.write(document.read())
file.close()
删除文件
- delect函数可以从GridFS中删除文件,同样只能通过主键删除(先查找到文件的主键)
from bson.objectid import ObjectId
book = gfs.find_one({"filename":"Python编程:从入门到实践.PDF"})
id = book._id
gfs.delete(ObjectId(id))