Query to get last X minutes data with Mongodb

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)