如何在nodejs中使用mongodb timestamp数据types?

我需要查询mongoosets字段,不能够这样做,因为mongoose不支持时间戳bson数据types? 任何想法如何在代码中查询ts?

我需要在mongo shell上做类似于这个查询的事情。

您可以直接从mongodb模块中使用mongodb时间戳,如以下示例中的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') 

build立连接后,可以使用与上面相同的概念,使用mongoose.connection.db.collection 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)); } }) });