2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

How to listen for changes to a MongoDB collection?

I"m creating a sort of background job queue system with MongoDB as the data store. How can I "listen" for inserts to a MongoDB collection before spawning workers to process the job? Do I need to poll every few seconds to see if there are any changes from last time, or is there a way my script can wait for inserts to occur? This is a PHP project that I am working on, but feel free to answer in Ruby or language agnostic
userimage

MongoDB has what is called capped collections and tailable cursors that allows MongoDB to push data to the listeners.

A capped collection is essentially a collection that is a fixed size and only allows insertions. Here's what it would look like to create one:

db.createCollection("messages", { capped: true, size: 100000000 }) 

Ruby example of using tailable cursors:

coll = db.collection('my_collection')

cursor = Mongo::Cursor.new(coll, :tailable => true)

loop do  

    if doc = cursor.next_document  

          puts doc  

    else    

         sleep 1  

    end

end

Answer is