Query to get last X minutes data with Mongodb
mongodb
Solution
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}},
])
Problem
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}); ``` But I'm trying to get a set with the value fields and timestamps from 18 minutes ago.