使用Mongodb查询以获取最近X分钟的数据 [英] Query to get last X minutes data with Mongodb
问题描述
我从mongodb开始,正在尝试查询具有以下文档格式的数据库:
I'm beginning with mongodb, and I'm trying to query my db that have this document format:
{ "_id" : ObjectId("520b8b3f8bd94741bf006033"), "value" : 0.664, "timestamp" : ISODate("2013-08-14T13:48:35Z"), "cr" : ISODate("2013-08-14T13:50:55.834Z") }
我可以使用以下查询从日期时间获取最后一条记录:
I can get the last records from a datetime with this query:
> db.mycol.find({timestamp:{$gt: ISODate("2013-08-14T13:48:00Z")}}).sort({x:1});
但是我试图从18分钟前开始获取一个包含值字段和时间戳的集合,如何建立对此的查询? 谢谢大家的耐心...
But I'm trying to get a set with the value fields and timestamps from 18 minutes ago, how can I build a query for this? Thanks everybody for your patience...
推荐答案
在18分钟的时间里,这与MongoDB无关,而与JavaScript和mongo shell中可用的内容有关:
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)
}
}
可以在mongo shell中运行,但是将Mongo驱动程序用于其他语言的确会有所不同.
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,
}
同时应用:
db.mycol.find(query, projection).sort({timestamp: 1});
嗯,那仍然不是一个集合",因为可能有重复项.要摆脱它们,您可以使用聚合框架中的$group
:
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}},
])
这篇关于使用Mongodb查询以获取最近X分钟的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!