Databases Reference
In-Depth Information
Getting Started with GridFS: mongofiles
The easiest way to get up and running with GridFS is by using the
mongofiles
utility.
mongofiles
is included with all MongoDB distributions and can be used to upload,
download, list, search for, or delete files in GridFS. As with any of the other command-
line tools, run
mongofiles --help
to see the options available for
mongofiles
. The fol-
lowing session shows how to use
mongofiles
to upload a file from the filesystem to
GridFS, list all of the files in GridFS, and download a file that we've
previously uploaded:
$ echo "Hello, world" > foo.txt
$ ./mongofiles put foo.txt
connected to: 127.0.0.1
added file: { _id: ObjectId('4c0d2a6c3052c25545139b88'),
filename: "foo.txt", length: 13, chunkSize: 262144,
uploadDate: new Date(1275931244818),
md5: "a7966bf58e23583c9a5a4059383ff850" }
done!
$ ./mongofiles list
connected to: 127.0.0.1
foo.txt 13
$ rm foo.txt
$ ./mongofiles get foo.txt
connected to: 127.0.0.1
done write to: foo.txt
$ cat foo.txt
Hello, world
In the previous example, we perform three basic operations using
mongofiles
:
put
,
list
, and
get
. The
put
operation takes a file in the filesystem and adds it to GridFS,
list
will list any files that have been added to GridFS, and
get
does the inverse of
put
: it takes a file from GridFS and writes it to the filesystem.
mongofiles
also supports
two other operations:
search
for finding files in GridFS by filename and
delete
for
removing a file from GridFS.
Working with GridFS from the MongoDB Drivers
We've seen how easy it is to work with GridFS from the command line, and it's equally
easy to work with from the MongoDB drivers. For example, we can use PyMongo, the
Python driver for MongoDB, to perform the same series of operations as we did with
mongofiles
:
>>> from pymongo import Connection
>>> import gridfs
>>> db = Connection().test
>>> fs = gridfs.GridFS(db)
>>> file_id = fs.put("Hello, world", filename="foo.txt")
>>> fs.list()
[u'foo.txt']
>>> fs.get(file_id).read()
'Hello, world'