MogoDB4
from pymongo import MongoClient
#创建链接对象
conn=MongoClient('localhost',27017)
#创建集合对象和数据库对象
db=conn.stu
my_set=db.class1
索引
index=my_set.ensure_index('name')
创建复合索引
index=my_set.ensure_index([('name',1),('Age',1)])
创建唯一索引
index=my_set.ensure_index('name',unique=True)
创建稀疏索引
index=my_set.ensure_index('name',sparse=True)
查看集合中的索引
list_indexes
for i in my_set.list_indexes():
print(i)
删除索引
drop_index():删除某一个索引
my_set.drop_index('name_1')---------name_1是索引的名称
drop_indexes():删除所有索引
my_set.drop_indexes()
聚合操作
aggregate([])
参数:与mongoshell中聚合参数写法一致
返回值:迭代器,同find的返回值
l=[{'$group':{'_id':'$gender','count':{'$sum':1}}},
{'$match':{'count':{'$gt':1}}}
]
cursor=my_set.aggregate(l)
for i in cursor:
print(i)
Mongo大文件存储
from pymongo import MongoClient
import bson.binary
conn=MongoClient('localhost',27017)
db=conn.file
my_set=db.img
#存储
f=open('picture.jpg','rb')
#将读取的二进制流,变为bson格式二进制的字串
content=bson.binary.Binary(f.read())
my_set.insert({'filename':'picture.jpg','data':content})
conn.close()
> show dbs admin 0.000GB config 0.000GB file 0.005GB grid_db 0.005GB local 0.000GB stu 0.000GB > > show tables img
大文件的提取
from pymongo import MongoClient
import bson.binary
conn=MongoClient('localhost',27017)
db=conn.file
my_set=db.img
data=my_set.find_one({'filename':'picture.jpg'})
with open(data['filename'],'wb') as f:
f.write(data['data'])
conn.close()
浙公网安备 33010602011771号