I am new to mongoDB and pymongo, trying to learn how to load and save databases from/to disk so that I can carry it around, to send it to people etc. I've read the tutorial on http://api.mongodb.org/python/current/tutorial.html but couldn't find useful information about saving and loading a db.
Assuming we create a database like:
import pymongo
mongo = pymongo.Connection()
db = mongo['my_db']
col = db['my_col']
col.insert({'name': 'Adam','occupation': 'student'})
col.insert({'name': 'John','occupation': 'officer'})
#how can we save the database to disk after this point
#and later read it from another program?
MongoDB files are portable and there are a couple of ways to achieve what you are looking for:
Copy the data directory for mongod
to another computer. This directory is normally based in /data/db/mongodb
. On the other computer you would simply replace the remote directory with the one you copied and restart the remote mongod
at which point you will have the data on their system. As far as I know MongoDB has no hot swap feature here whereby you can switch, on-demand, the directories without downtime.
Make hot backups of your data and use MongoDBs export and import functions to select subsets of data to place onto the remote machine. You would do hot backup via mongodump
and mongorestore
. You can find the general doc page on that here: http://docs.mongodb.org/manual/administration/backups/#using-binary-database-dumps-for-backups
Make CSV/JSON exports of your data and import it onto the remote computer. This is a lot like the binary backups in this particular scenario except they are also more readable to end parties etc. I should also note that this method only inserts, it is the same as a batch insert client side iterating (in something like PHP) a CSV and calling a batch insert on the MongoDB server. You can find more information about mongoexport
and mongoimport
(the programs that do this) here: http://docs.mongodb.org/manual/administration/import-export/
You can also find nice general information that relates to backing up data and moving it and restoring it on foreign machines here: http://docs.mongodb.org/manual/administration/backups/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With