您可以直接从 mongodb 模块使用 mongodb Timestamp,如以下示例MongoDB Oplog & Node.js所示,该示例演示了查询 oplog 以获得最高时间戳:
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);
});
});
});
Run Code Online (Sandbox Code Playgroud)
使用 mongoose,您可以说例如连接到找到 oplog 的本地数据库:
var MongoDB = require('mongodb');
mongoose.connect('mongodb://localhost/local')
Run Code Online (Sandbox Code Playgroud)
建立连接后,您可以使用与上面相同的概念,在使用该mongoose.connection.db.collection('oplog.rs')对象的“oplog.rs”集合上使用可尾游标,例如:
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));
}
})
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8910 次 |
| 最近记录: |