Listening from Mongodb always and triggering I am using classes for the first time. In this program I want the object to run infinitely so that any change in the MongoDB will trigger the function and do the necessary processing.

I am little confused about the using of the self. Please give me feedback on my code.Thanks!

class first_level:




    def __init__(self):

        import pymongo
        connection = pymongo.MongoClient("mongodb://localhost")

        self.test_3_dec = connection.test_3_dec
        self.test1 = self.test_3_dec.test1
        self.test2 = self.test_3_dec.test2




    def listener_function(self):

        cursor = self.test2.find({},{"check_bit":True,"_id":True})

        for bit in cursor:
            if bit["check_bit"]==0:
                self.update_function(bit["check_bit"],bit["_id"])

    def update_function(self,value,value2):

        self.test1.insert({"_id":value2,"bit":value})

        self.test2.update({"_id":value2},{"$set":{"check_bit":1}})


obj = first()

while True:
    obj.listener_function()
I'm in doubt if your code actually works as you instantiate using obj = first(), but your class is named first_level(). This kind of indicates that either you've left out code, or you have broken code. 

Anyway, here are some pointers for you:


Imports should go at start of file – It's generally considere bad style to import stuff within classes or functions
The connection you create is forgotten – You should store the connection, as it is killed when __init__ is completed. You should use something like self.connection = pymongo.... If your code actually is working, then it is because the self.testXXX keeps it alive
Vertical space is good, but you've got too much – The common policy is to have two blank lines in front off functions and classes, and single lines in front of different part you want to differentiate a little from other blocks.
Increase horizontal space – After commas or colons you could benefit from adding spaces. Instead of insert({"_id":value2,"bit":value}) do insert({"_id": value2, "bit": value})
Add comments and/or docstrings – It is hard to read what your code actually does, and why it does it. This should be commented upon.
Avoid busy tight loops – Doing while True with a single function not doing much, is a tight busy loop, and should usually be avoided. At least if doing it this way, you should add a sleep somewhere to avoid hogging resources.


A better solution related to MongoDb

However instead of doing a busy loop with some code which I don't fully grasp, I believe you should look into the monitoring of the mongodb. This would allow you to get notified when commands are executed against the mongodb.

At least, that is how I read the documentation, with little knowledge of mongodb. And this pattern of adding a listener, and then waiting for it to respond is a bettern pattern rather than busy waiting and changing stuff to check if it is alive.