我需要在mongoose中查询oplog ts字段,因为mongoose不支持Timestamp bson数据类型,所以不能这样做?知道如何在代码中查询ts?
我需要在mongo shell上执行与this查询类似的操作。
答案 0 :(得分:3)
您可以直接从mongodb模块使用mongodb Timestamp,如以下示例 The 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);
});
});
});
使用mongoose,您可以说连接到找到oplog的本地数据库:
var MongoDB = require('mongodb');
mongoose.connect('mongodb://localhost/local')
建立连接后,您可以使用与上面相同的概念在&#34; oplog.rs&#34;上使用tailable游标。使用mongoose.connection.db.collection('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));
}
})
});