27

我正在尝试查询具有此文档格式的数据库:

{
  "_id" : ObjectId("520b8b3f8bd94741bf006033"),
  "value" : 0.664,
  "timestamp" : ISODate("2013-08-14T13:48:35Z"),
  "cr" : ISODate("2013-08-14T13:50:55.834Z")
}

我可以使用此查询从日期时间获取最后一条记录:

db.mycol.find({timestamp:{$gt: ISODate("2013-08-14T13:48:00Z")}}).sort({x:1});

但我试图从 18 分钟前获得一个包含值字段和时间戳的集合。

4

5 回答 5

69

For the 18 minutes part, that's not really about MongoDB, but about JavaScript and what's available in the mongo shell:

query = {
    timestamp: { // 18 minutes ago (from now)
        $gt: new Date(ISODate().getTime() - 1000 * 60 * 18)
    }
}

Works in the mongo shell, but using Mongo drivers for other languages would be really different.

To "project" over a smaller schema with both values and timestamps:

projection = {
    _id: 0,
    value: 1,
    timestamp: 1,
}

Applying both:

db.mycol.find(query, projection).sort({timestamp: 1});

Well, that's still not a "set" since there might be duplicates. To get rid of them you can use the $group from the aggregation framework:

db.mycol.aggregate([
    {$match: query},
    {$group: {
        _id: {
            value: "$value",
            timestamp: "$timestamp",
        }
    }},
    {$project: {
        value: "$_id.value",
        timestamp: "$_id.timestamp",
    }},
    {$sort: {timestamp: 1}},
])
于 2013-08-14T14:46:15.430 回答
7

你也可以在下面做

  db.getCollection('collectionName').find({timestamp : {$gte: new Date().getTime()-(60*60*1000) } } )

上面的查询将为您提供现在和 60 分钟的时间戳记录。如果您喜欢超过 60 分钟 - 比如说 2 小时,您可以将表达式更改为 (2*60*60*1000) 30 分钟 (30*60*1000)

于 2020-02-18T21:49:58.380 回答
2

您可以使用 nodejs 从 mongodb 访问当前时间戳的数据

 const collection1 = dbo.collection('customers');
    var dateq = new Date();
      collection1.find({    "Timestamp" : { $gt: new Date(dateq.getTime() - 6000)}  
    }).toArray(function(err , docs){   
    console.log(docs);
    }

代码结束

于 2019-03-11T10:50:26.190 回答
1

哇,感谢@Alistair_Nelson,我能够从 n 分钟前获取数据,例如从 ISODate("2013-08-14T14:00:00Z") 获取最后 18 分钟:

db.mycol.find({timestamp:{$gt: new Date(ISODate("2013-08-14T14:00:00Z")-18*60000)}})

只获取我需要的字段:

db.mycol.find({timestamp:{$gt: new Date(ISODate("2013-08-14T14:00:00Z")-18*60000)}},{value:1,timestamp:1, _id:0})
于 2013-08-14T14:42:24.260 回答
0

从 开始Mongo 5,您可以使用$dateSubtract

// { date: ISODate("2021-12-05T20:32:56Z") } <= 5  minutes ago
// { date: ISODate("2021-12-05T20:07:56Z") } <= 25 minutes ago (older than 18 minutes)
db.collection.aggregate([
  { $match: {
    $expr: {
      $gt: [
        "$date",
        { $dateSubtract: { startDate: "$$NOW", unit: "minute", amount: 18 } }
      ]
    }
  }}
])
// { date: ISODate("2021-12-05T20:32:56Z") } <= 5 minutes ago

使用$dateSubtract,我们通过从当前日期( ) 中减去18( amount) "minute"( ) 来创建保存文档的最早日期/时间。unit$$NOWstartDate

于 2021-12-07T19:37:32.800 回答