mongodb存储二进制数据的二种方式——binary bson或gridfs

python 版本为2.7

mongodb版本2.6.5

 

使用mongodb存储文件,可以使用两种方式,一种是像存储普通数据那样,将文件转化为二进制数据存入mongodb,另一种使用gridfs,咱们先来说说第一种

 

先读取文件内容,然后塞进bson.binary.Binary对象里,最后像平常那样写入数据库,是不是很简单呢,获取文件一样的简单,像平时那样查找数据,然后将二进制内容写入文件即可

 

#coding=utf-8
''' Created on 2015-10-8 @author: kwsy2015 ''' import pymongo import bson.binary from pymongo import MongoClient from cStringIO import StringIO def insertFile(): client = MongoClient('localhost', 27017) #获得一个database db = client.MongoFile #获得一个collection coll = db.image filename = 'F:/测试数据/hehe.jpg'.decode('utf-8') with open (filename,'rb') as myimage: content = StringIO(myimage.read()) coll.save(dict( content= bson.binary.Binary(content.getvalue()), filename = 'hehe.jpg' )) def getFile(): client = MongoClient('localhost', 27017) #获得一个database db = client.MongoFile #获得一个collection coll = db.image data = coll.find_one({'filename':'hehe.jpg'}) out = open('F:/测试数据/test4.jpg'.decode('utf-8'),'wb') out.write(data['content']) out.close() getFile()

因为我的文件路径都带有中文,因此需要用utf-8解码,否则会报错的

 

使用上述方法存储小文件是很方便的,那么如果是大文件呢,可以使用gridfs

        gridfs会把文件分成若干块来存储,每一块的大小默认为256K,所以,如果是小文件,就不要用gridfs来存储了,不然会浪费空间的,gridfs是MongoDB之上的分布式文件系统,可以使用mongodb的分片和复制机制,因为Mongodb分配数据空间时以2GB为单位,所以gridfs不产生磁盘碎片。

        

#coding=utf-8
''' Created on 2015-9-29 @author: Administrator ''' from pymongo import MongoClient from bson.objectid import ObjectId from gridfs import * def insertFile(): client = MongoClient('localhost', 27017) db = client.Pic fs = GridFS(db, 'images') with open ('F:/测试数据/hehe.jpg'.decode('utf-8'),'rb') as myimage: data=myimage.read() id = fs.put(data,filename='first') print id def getFile(): client = MongoClient('localhost', 27017) db = client.Pic fs = GridFS(db, 'images') file = fs.get_version('first', 0) data = file.read() out = open('F:/测试数据/test3.jpg'.decode('utf-8'),'wb') out.write(data) out.close() def delFile(): client = MongoClient('localhost', 27017) db = client.Pic fs = GridFS(db, 'images') fs.delete(ObjectId('560a531b0d4eae34a4edbfdd')) def listName(): client = MongoClient('localhost', 27017) db = client.Pic fs = GridFS(db, 'images') print fs.list() listName()

写入文件时,我们可以设置它的filename,如果多个文件使用同一个filename呢,我们在获取文件时可以使用get_version()函数,第一个参数是filename,第二个参数是版本,从0开始。

 

此外,我们还可以使用get(),函数,需传入文件的ObjectId

使用python操作gridfs总得来说是很方便的,毕竟所提供的函数就那么几个,稍微用心看看源码就没问题了

 

转自:http://www.voidcn.com/blog/KWSY2008/article/p-4871553.html

    原文作者:MongoDB
    原文地址: https://www.cnblogs.com/bonelee/p/6513657.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞