Some aggregate query methods in Python MongoDB

Keywords: Python MongoDB

MongoDB's aggregate query grammar has always made it difficult for me to get started very well. If it wasn't for project needs, I would seldom use it. But after using more, I would like it more and more. Especially after I came into contact with some aggregate query methods, I found that MongoDB has really improved a lot of efficiency in business. In short, MongoDB is really fragrant ~~~

Here are some of my usual records of using aggregated queries

Data set data format

{
    "_id" : ObjectId("5caef7f2c0cd2730919a038f"),
    "sn" : "1904010010000001",
    "dev_id" : 200,
    "dt" : ISODate("2036-02-07T14:29:00.000Z"),
    "data" : {
        "BT" : 20.0,
        "CSQ" : 23,
        "GPSLati" : 39.8679244,
        "GPSLongti" : 116.6568387,
        "Humidity" : 0.0,
        "Temprature" : 0.0,
        "Voltage" : 0.0
    }
}

Query the latest data under all SNS

sn = ['1904010010000001', '1904010010000002', '1904010010000003']
pipeline = [
    {'$match': {'sn': {'$in': sn}}},
    {'$group': {'_id': "$sn", "data": {'$last': "$data"}, "dt": {'$last': "$dt"}}},
    {'$sort': {"dt": 1}}]

db.data.aggregate(pipeline)

Return results (to avoid data being too long, showing only one data)

[
    {
        '_id': '1812010009000100',
        'data': {
            'Ap': 1009.7, 'BT': 20.0, 'CSQ': 24, 
            'GPSLati': 39.8681678, 'GPSLongti': 116.6591262, 
            'Humidity': 31.400000000000002, 'Temprature': 21.5, 
            'Voltage': 0.98, 'WindDir': 0, 'WindSpeed': 0.0
        }, 
        'dt': datetime.datetime(2019, 4, 14, 17, 44)
    }
]

Query the average of statistics for a Sn every 10 minutes in 10 hours

sn = '1904010010000001'
pipeline = [
    {'$project': {'date': {'$substr': ["$dt", 0, 15]}, 'data': '$data'}},
    {'$group': {
        '_id': "$date",
        'temprature': {'$avg': '$data.Temprature'},
        'humidity': {'$avg': '$data.Humidity'},
        'wind_speed': {'$avg': '$data.WindSpeed'},
        'wind_dir': {'$avg': '$data.WindDir'}
    }},
    {'$limit': 60},
    {'$sort': {'_id': -1}}
]

db.data.aggregate(pipeline)

Return results (to avoid data being too long, showing only one data)

[
    {
        '_id': '2019-04-14T01:3', 
        'temprature': 10.861538461538462, 
        'humidity': 18.70769230769231, 
        'wind_speed': 0.49230769230769234, 
        'wind_dir': 167.6153846153846
    }
]

Original address: Some aggregate query methods in Python MongoDB
My blog: Spatio-temporal router

Posted by Xager on Sun, 14 Apr 2019 19:18:31 -0700