如何在nodejs中使用mongodb时间戳数据类型?

dha*_*val 4 mongoose mongodb node.js

我需要查询 mongoose 中的 oplog ts 字段,但由于 mongoose 不支持 Timestamp bson 数据类型而无法这样做?知道如何在代码中查询 ts 吗?

我需要在 mongo shell 上执行类似于查询的操作。

chr*_*dam 5

您可以直接从 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)

  • [**`Timestamp()`**](https://mongodb.github.io/node-mongodb-native/api-bson- generated/timestamp.html) 构造函数中的第一个参数代表低位(有符号)时间戳的 32 位,因此当它来自 mongo 时,它是 1,因为它代表前 32 位,即“time_t”值(自 Unix 纪元以来的秒数)。有关更多信息,请参阅文档[**此处**](https://docs.mongodb.org/manual/reference/bson-types/#timestamps) (2认同)