MongoDB, pymongo and GridFS

11 Sep

It has been a while since I’ve done anything with MongoDB-I changed jobs and don’t get to code much anymore. I had the urge to learn more and was interested in storing files in MongoDB using GridFS. I googled, read StackOverflow and MongoDB in Action. The problem was most info was storing text as a file or even when storing a file, the code got the _id when executing the put. So of course get is easy, you have the id. Figuring how to get after the fact was where I got stuck, also had to switch file operations to binary. Here is what I have for putting a file in MongoDB and how to retrieve it later.

from pymongo import MongoClient
import gridfs

client=MongoClient()
db=client.mytest
data=open(“image.png”,”rb”)
fs=gridfs.GridFS(db)
thedata=data.read()
stored=fs.put(thedata,filename=”inmongoimage”)

To get it back in the same code you call:
out=fs.get(stored).read()

This works because stored has the _id of the put operation. But what if I need to retrieve in different code from the inserts? Here is how I got it out with some extra code for info:
imports….
client=MongoClient()
db=client.mytest
fs=gridfs.GridFS(db)

filelist=fs.list()
#returns the file names stored

fileone=filelist[0].encode(“ascii”,”ignore”)
#returns a string of the first file name

outdata=fs.get_version(fileone,”rb”).read()
output=open(“somefile.png”,”wb”)
output.write(outdata)
output.close()

Put allows for more metadata than just the filename:
fs.put(thedata,filename=”file.jpg”,field=”string of text”,anumberfield=52)

To find on a different field:
fs.get_version(anumberfield=52)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: