MongoDB的.读取,搜索基于oplog的时间戳

Rif*_*331 5 mongodb

> db.oplog.rs.find({},{"ts":1}).sort({$natural: -1})
{ "ts" : Timestamp(1406185666, 1) }  
{ "ts" : Timestamp(1406180043, 1) }  
{ "ts" : Timestamp(1406180033, 1) }  
{ "ts" : Timestamp(1406172831, 1) }  
{ "ts" : Timestamp(1406171938, 1) }  
{ "ts" : Timestamp(1405915291, 1) }  
{ "ts" : Timestamp(1405915131, 1) }  
{ "ts" : Timestamp(1405915019, 1) }  
{ "ts" : Timestamp(1405914592, 1) }  
{ "ts" : Timestamp(1405914581, 1) }  
{ "ts" : Timestamp(1405587944, 1) }  
{ "ts" : Timestamp(1405587920, 1) }  
{ "ts" : Timestamp(1405587468, 1) }  
{ "ts" : Timestamp(1405587432, 1) }  
{ "ts" : Timestamp(1405587393, 1) }  
{ "ts" : Timestamp(1405587294, 1) }  
{ "ts" : Timestamp(1405587074, 1) }  
{ "ts" : Timestamp(1405586117, 1) }  
{ "ts" : Timestamp(1405586069, 1) }  
{ "ts" : Timestamp(1405586054, 1) }  
Run Code Online (Sandbox Code Playgroud)

我在我的数据库中的oplog.rs中有一系列时间戳示例.我不知道怎么读

我的问题是:

  1. 让我们说今天是2014年8月13日8:28.我想从最后一小时选择所有的oplog
  2. 我希望从2014年8月12日9:00到15:00看到所有的oplog.

wdb*_*ley 7

Timestamp您在oplog中看到的值是内部MongoDB BSON类型.es表示为函数的第一个参数Timestamp(es, ord)time_t自Unix纪元以来的秒值.第二个是在一秒钟内订购时间戳的序数.你应该能够查询Timestamp通常以s $gt,$lt等:

> db.ts.find()
{ "_id" : ObjectId("53eb914ff9b63e0dd3ca1a20"), "ts" : Timestamp(1406185666, 1) }
{ "_id" : ObjectId("53eb915cf9b63e0dd3ca1a21"), "ts" : Timestamp(1405914581, 1) }
{ "_id" : ObjectId("53eb917cf9b63e0dd3ca1a22"), "ts" : Timestamp(1406185666, 2) }

> db.ts.find({ "ts" : { "$gte" : Timestamp(1406185630, 1) } })
{ "_id" : ObjectId("53eb914ff9b63e0dd3ca1a20"), "ts" : Timestamp(1406185666, 1) }
{ "_id" : ObjectId("53eb917cf9b63e0dd3ca1a22"), "ts" : Timestamp(1406185666, 2) }

> db.ts.find({ "ts" : { "$gt" : Timestamp(1406185666, 1) } })
{ "_id" : ObjectId("53eb917cf9b63e0dd3ca1a22"), "ts" : Timestamp(1406185666, 2) }
Run Code Online (Sandbox Code Playgroud)

要回答你的具体问题(在mongo shell中),

让我们说今天是2014年8月13日8:28.我想从最后一小时选择所有的oplog

> var SECS_PER_HOUR = 3600
> var now = Math.floor((new Date().getTime()) / 1000) // seconds since epoch right now
> db.oplog.rs.find({ "ts" : { "$lt" : Timestamp(now, 1), "$gt" : Timestamp(now - SECS_PER_HOUR, 1) } })
Run Code Online (Sandbox Code Playgroud)

我希望从2014年8月12日9:00到15:00看到所有的oplog

您没有指定时区 - 请务必小心并做出正确的选择.

> var since = Math.floor(ISODate("2014-08-12T09:00:00.000Z").getTime() / 1000)
> var until = Math.floor(ISODate("2014-08-12T15:00:00.000Z").getTime() / 1000)
> db.oplog.rs.find({ "ts" : { "$lt" : Timestamp(until, 1), "$gt" : Timestamp(since, 1) } })
Run Code Online (Sandbox Code Playgroud)

  • 我们如何在 nodejs 中做到这一点说猫鼬? (2认同)