I'm trying to develop a Log Viewer using DerbyJS, Racer and MongoDB. The logs will be inserted into the MongoDB database by a different source continuously, and my Log Viewer should be able to update the Logs Table on the user interface automatically.
I was wondering if there is a native way of listening to MongoDB events, like:
- On update
- On delete
These would be similar to, for example, Oracle DB triggers.
You can listen to events like insert
, update
, and other data events in mongodb using special collection named oplog
. You just need to enable replication on your db instance either using mongod --master
or mongod --replicaSet
.
Oplog is actually a capped collection which is used by mongodb internally to implement replication. If you are using master/slave replication you will find the collection by the name of oplog.$main
, if you are using replica sets it will be named oplog.rs
.
You can use a tailable cursor on oplog, that should work.
Oplog, in effect, is logs itself. So you might not need to store them separately for logging purpose. However its size is fixed. Meaning when its full, older data gets deleted.
local
database, thats where oplogs are maintainedHere is a working example from mongoskin wiki page
skin = require "mongoskin"
db = skin.db "localhost:27017/local"
#//Cursor on oplog (a capped collection) which maintains a history for replication
#//oplog can be used only when replication is enabled
#//Use oplog.rs instead of oplog.$main if you are using replica set
oplog = db.collection "oplog.$main"
cursor = oplog.find({'ns': "icanvc.projects"},{tailable: yes, awaitData: yes})
#//Using cursor.nextObject will be slow
cursor.each (err, log)->
console.error err if err
console.log log if not err