How-to write Python for MongoDB

First of all, you need to install the Python driver for MongoDB module, pymongo. The easiest way is to use pip or easy_install to install it.

$ pip install pymongo
or
$ easy_install pymongo

Then, you can start to write scripts. Here is an example:

#!/usr/bin/python
'''
Create a user
'''
import pymongo
from pymongo import Connection
from pymongo import master_slave_connection
from pymongo import database
from pymongo import cursor


    def __do_create_mongouser(self):
        isSuccess = False
        
        mongo_user = self.newuser
        mongo_pass = self.newuser
        mongo_db = self.newuser
        
        
        try:
            #connect to mongodb andget authenticated

            '''
                before connect, modify the connect string as:
                "vip:port,vip2:port..." so that this can be used in Connection()
                the vip str should be like "vip1,vip2,vip3",
                and we regard all port are the same.
            '''
            vip_list = self.vip.split(',')
            con_str = 'mongodb://'
            for item in vip_list:
                con_str += item + ':%d,' % self.port 
            con = con_str[:-1]
            c = Connection(con, replicaset=self.sid)

            db = database.Database(c, self.sysuser)
            db.authenticate(self.sysuser,self.syspass)
            
            #check if user exist: by check if database name exist(database name and username are the same) 
            database_names = c.database_names()
            #if "u'"+self.newuser+"'" in database_names:
            if mongo_user in database_names:
                raise DbUserCreateError('DbUserCreateError: In Remote Oracle DB User [' + 
                                        mongo_user + '] Already Exists.')
            db_new = database.Database(c, mongo_db)
            db_new.add_user(mongo_user, mongo_pass)
        #except pymongo.errors.AutoReconnect as e:
            #auto reconnect once ... skip
        except pymongo.errors.PyMongoError as e:
            
            self.logger.error(e)
            raise
        else:
            isSuccess = True
            self.logger.info('Create Mongo User&DB[' + mongo_user + '] Success!')
        finally:
            try:
                c.disconnect()
            except Exception as e:
                self.logger.error(e)
        
        return { 
                'username': mongo_user,
                'password': mongo_pass,
                'db': mongo_db,
                'success' : isSuccess ,
               }


    def __do_drop_mongouser(self, db_item):
        sysuser = db_item['admin_user']
        syspass = db_item['admin_passwd']
        vip = db_item['vip']
        port = db_item['db_port']
        sid = db_item['sid']
        olduser = db_item['olduser']

        try:
            '''
                before connect, modify the connect string as:
                "vip:port,vip2:port..." so that this can be used in Connection()
                the vip str should be like "vip1,vip2,vip3",
                and we regard all port are the same.
            '''
            vip_list = vip.split(',')
            con_str = 'mongodb://'
            for item in vip_list:
                con_str += item + ':%d,' % port 
            con = con_str[:-1]

            c = Connection(con, replicaset=sid)
            #c = Connection(vip,int(port))
            db = database.Database(c, sysuser)
            db.authenticate(sysuser,syspass)

            #1 drop mongo user. don't need to check exist or not as MongoDB can handle it implicitly
            db_old = database.Database(c, olduser)
            db_old.remove_user(olduser)
        except pymongo.errors.AutoReconnect as e:
            #auto reconnect once

            c = Connection(con, replicaset=sid)
            #c = Connection(vip,int(port))
            db = database.Database(c, sysuser)
            db.authenticate(sysuser,syspass)

            #1 drop mongo user.
            db_old = database.Database(c, olduser)
            db_old.remove_user(olduser)
        except pymongo.errors.PyMongoError as e:
            
            self.logger.error(e)
            raise DbUserDropError(str(e)) 
        else:
            self.logger.info('Drop Mongo User [' + olduser + '] Success!')

        #2 drop mongo database.
        try:
            c.drop_database(olduser)
        except TypeError as e:
            raise DbUserDropError("MongoDbUserDropError:" + e.message)
        else:
            self.logger.info('Drop Mongo DB [' + olduser + '] Success!')
        finally:
            c.disconnect()

Of course, it’s a quite simple example. But it’s a good and great start 🙂

Advertisements

About Alex Zeng
I would be very happy if this blog can help you. I appreciate every honest comments. Please forgive me if I'm too busy to reply your comments in time.

2 Responses to How-to write Python for MongoDB

  1. david Francois says:

    what version of python are you using?

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: