A little something extra for managing PyMongo

I really dislike boilerplate code, it drives me a little bit crazy. Starting database connections falls squarely into that realm. So in the vein of "sharing is caring" here is what I'm currently using with pymongo. It's pretty simple, but why code it twice right?

It's pretty simple script that only contains one class: MongoConnection. It needs to be initialized with a dictionary containing the connection parameters (preferably stored in a config file that you're just feeding in) like so.

settings = {
  'user' : 'username',
  'pasword' : 'password',
  'host' : 'hostname',
  'port' : 'port',
  'db': 'db_name',
  'collection': 'collection_name'

import MongoConnect as mcxn
dbConnection = mcxn.MongoConnection(settings)

With that it will have already initialized the specific database and collection needed, right away you can:

#Insert a document
dbConnection.collection.insert({"body": "I am a sample document body", "name": "FunnyBunny"})
#Find that document!
dbConnection.collection.find({"name" : "FunnyBunny"})
#Close the connection to the database!
#Reopen it after closing it! Just go wild!

So that's about it. There is some basic error handling, which is to say don't push it.

The previous code is scratched, a new better version can be found in a gist that I will regularly update. Alternatively, you can just copy this url and use wget to download the script :)