Query to get last X minutes data with Mongodb

2019-01-16 15:17发布

问题:

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});

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...

回答1:

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}},
])


回答2:

Wow, thanks to @Alistair_Nelson I was able to get the data from n minutes ago, for example to get the last 18 minutes from ISODate("2013-08-14T14:00:00Z"):

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

To get only the fields I need:

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


标签: mongodb