Skip to content

Instantly share code, notes, and snippets.

@ricleal
Created October 31, 2013 10:44
Show Gist options
  • Save ricleal/7247685 to your computer and use it in GitHub Desktop.
Save ricleal/7247685 to your computer and use it in GitHub Desktop.
Generic mongodb class written in pymongo. It depends from a log and a configparser. Those dependencies are simple to delete.
from pymongo import MongoClient
import logging
logger = logging.getLogger(__name__)
from config.config import configParser
class Database(object):
'''
Generic class to access MongoDB.
Uses / create a database accordinf to instrument name
'''
db = None
collections={}
def __init__(self,databaseNamePrefix='reduction'):
'''
Constructor
'''
self.client = MongoClient() # localhost
databasename = databaseNamePrefix + configParser.get("General", "instrument_name")
self.db = self.client[databasename]
logger.debug("Using database: %s."%databasename)
def createCollection(self, name, max=22, size=10240, capped=True):
"""
Create a collection.
@param name:
@param max:
@param size:
@param capped:
"""
try:
self.collections[name] = self.db.create_collection( name=name, size=size, capped=capped,max=max )
logger.debug("Collection %s created."%name)
except:
# Assuming it becauase name in self.db.collection_names()
logger.info("Collection %s already exist. Skipping creation..."%name)
self.collections = self.db[name]
def dumpCollectionToArray(self,collectionName,constraint={}):
"""
@param collectionName: name
@param constraint: constraing for collection.find()
"""
#from bson.json_util import dumps
#return dumps(cursor)
cursor = self.collections[collectionName].find(constraint);
return [i for i in cursor]
def __del__(self):
self.client.close()
def dropDatabase(self):
"""
Never use this one :)
"""
self.db.drop()
if __name__ == '__main__':
db = Database()
db.createCollection('numors')
db.createCollection('queries')
for i in range(1000,1020):
db.collections['numors'].insert({"numor": i, "filename": "/tmp/file_%d.nxs"%i})
db.collections['queries'].insert({"query_id" : "001","numor": [1000,1001,1002]})
objectId = db.collections['queries'].insert({"query_id" : "002","numor": [1004,1005,1006]})
# modifify
db.collections['queries'].save({ "_id": objectId, "query_id" : "002","numor": [1004,1005,1007]})
import pprint
pprint.pprint(db.dumpCollectionToArray('queries'))
pprint.pprint(db.dumpCollectionToArray('numors'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment