标签:pytho update upd tor type *args document insert rom
驱动模块
pip install pymongo
创建连接
from pymongo import MongoClient
client = MongoClient(host="localhost",port=27017)
client.admin.authenticate("admin","123456")
数据写入
client.school.student.insert_one({"name":"alex"})
client.school.student.insert_many({"name":"bob"},{"name":"cindy"})
数据查询
student = client.school.student.find_one({"name":"alex"})
print(student)
students = client.school.student.find({})
for one in students:
print(one["_id"],one["name"])
students = client.school.student.find({}).skip(0).limit(10)
count = client.school.student.count_documents({})
students = client.school.student.distinct("name")
students = client.school.student.find().sort([("name",-1)])
数据修改
client.school.student.update_one({"name":"alex"},{"$set":{"sex":"女"}})
client.school.student.update_many({},{"$set":{"grade":"七年级"}})
数据删除
client.school.student.delete_one({"name":"alex"})
client.school.student.delete_many({})
存储文件
连接GridFS
from gridfs import GridFS
db = client.school
gfs = GridFS(db,collection="book")
保存文件
file = open("D:/Python编程:从入门到实践.pdf","rb")
args = {"type":"PDF","keyword":"Python"}
gfs.put(file,file="Python编程:从入门到实践.PDF",**args)
file.close()
查找文件
book = gfs.find_one({"filename":"Python编程:从入门到实践.PDF"})
print(book.keywode)
books = gfs.find({"type":"PDF"})
for one in books:
print(one.filename)
判断是否存储了文件
rs = gfs.exists({"filename":"Python编程:从入门到实践.PDF"})
print(rs)
读取文件
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()
删除文件
from bson.objectid import ObjectId
book = gfs.find_one({"filename":"Python编程:从入门到实践.PDF"})
id = book._id
gfs.delete(ObjectId(id))
标签:pytho update upd tor type *args document insert rom
原文地址:https://www.cnblogs.com/felixqiang/p/11221507.html