This example uses tailable cursor to wait data that inserted to mongodb. Tailibale cursor is like tail -f command in Unix.

To use this example collection should be capped (only capped collections support Tailable Cursor). Capped collection is fixed-sized collection that automatically overwrites its oldest entries when it reaches its maximum size. To create it in mongo client:

run db.createCollection('messages', { capped: true, size: 100000 });

var mongo = require("mongodb"), // mongodb client
    io = require(""),  // socket io server
    http = require("http");

var app = http.createServer((req, res) => {
    res.end(" example");

io = io.listen(app);
console.log("http server on port 3000");

mongo.MongoClient.connect ('mongodb://', (err, db) => {
  // db initialized

  db.collection('messages', function(err, collection) {
    // Grab the messages collection

    io.sockets.on("connection", function (socket) {
      // when client connects

      // open a tailable cursor, and find all documents
      collection.find({}, {
        tailable:true, // the cursor is tailable
        awaitdata:true, //  allow the cursor to wait for data
        numberOfRetries:-1 // the number of times to retry on timeout.
      }).sort({ $natural: 1 }).each((err, doc) => {

        // send message to client
        if (doc.type == "message") {