python与mongo_MongoDB与Python的交互

驱动模块

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))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值