Query to get last X minutes data with Mongodb

前端 未结 4 1639
有刺的猬
有刺的猬 2020-12-04 16:11

I\'m beginning with mongodb, and I\'m trying to query my db that have this document format:

{ \"_id\" : ObjectId(\"520b8b3f8bd94741bf006033\"), \"value\" : 0         


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-04 16:42

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

提交回复
热议问题