dhaval
dhaval

Reputation: 2388

How to use mongodb timestamp datatype in nodejs?

I need to query oplog ts field in mongoose, not able to do so since mongoose does not support Timestamp bson data type? Any idea how to query ts in code?

I need to do something similar to this query on mongo shell.

Upvotes: 4

Views: 9135

Answers (1)

chridam
chridam

Reputation: 103305

You can use mongodb Timestamp directly from the mongodb module as in the following example The MongoDB Oplog & Node.js which demonstrates querying the oplog for the highest timestamp :

var MongoDB = require('mongodb');

// get the oplog URL
oplogurl = 'mongodb://<user>:<password>@candidate.11.mongolayer.com:10240,candidate.0.mongolayer.com:10240/local?authSource=wiktory'

// open db connection 
MongoDB.MongoClient.connect(oplogurl, function(err, db) {  

    // get oplog collection
    db.collection("oplog.rs", function(err, oplog) {

        // find the highest timestamp
        var ts = new MongoDB.Timestamp(0, Math.floor(new Date().getTime() / 1000)),
            query = { "$gt": ts };

        // create a tailable cursor and set it to await data
        cursor = oplog.find({ ts: query }, {
            tailable: true,
            awaitdata: true,
            oplogReplay: true,
            numberOfRetries: -1
        });

        // wrap that cursor in a Node Stream
        stream = cursor.stream();

        // log to console when data arrives
        stream.on('data', function(oplogdoc) {
            console.log(oplogdoc);
        });

    });
});

With mongoose, you can say for instance connect to to the local database where the oplog is found:

var MongoDB = require('mongodb');
mongoose.connect('mongodb://localhost/local')

Once a connection is established, you can then use the same concept as above to use a tailable cursor on the "oplog.rs" collection using the mongoose.connection.db.collection('oplog.rs') object, for example:

var mongoose = require('mongoose');
var MongoDB = require('mongodb');
mongoose.connect('mongodb://localhost/local');  

var conn = mongoose.connection;
conn.on('error', console.error.bind(console, 'connection error:'));
conn.once('open', function callback () {

    var oplog = conn.db.collection('oplog.rs');

    // find the highest timestamp
    var ts = new MongoDB.Timestamp(0, Math.floor(new Date().getTime() / 1000)),
        query = { "$gt": ts };

    // create a tailable cursor and loop each oplog entry
    oplog.find({ ts: query }, { tailable: true }).each(function(err, entry) {
        if (err) { /* handle error */ } 
        else {
            // log new oplog entry                                                                                                                                           
            console.log(JSON.stringify(entry));
        }
    })
});

Upvotes: 5

Related Questions