Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve last document in a MongoDB using Pymongo and Flask

I'm working on a Raspberry Pi project that collects weather measurements and stores them in a Mongo database like this:

{
    "_id": {
        "$oid": "577975c874fece5775117209"
    },
    "timestamp": {
        "$date": "2016-07-03T20:30:00.995Z"
    },
    "temp_f": 68.9,
    "temp_c": 20.5,
    "humidity": 50,
    "pressure": 29.5
}

The data is going into the Mongo db just fine. Next, I'm trying to build a Flask-based dashboard that enables me to look at the recorded data. On one of the pages of the dashboard, I want to show the current recorded values, so what I need to do is pull out the last measurement and pass it to a flask template for rendering to the browser.

I found a post here that said I could use:

data = db.measurements.find().limit(1).sort({"$natural": -1})

but natural doesn't seem to be a valid option for the call to find.

This works:

measurement = mongo.db.measurements.find_one()

It pulls back one random measurement that I can then pass to the flask template, but how do I use sort to get the most recent one?

I tried:

measurement = mongo.db.measurements.find_one().sort([("timestamp", -1)])

but that generates an attribute error: AttributeError: 'dict' object has no attribute 'sort'

I've also tried:

cursor = mongo.db.measurements.find().limit(1).sort({"timestamp": -1})

but that doesn't work either.

I'm missing something here, can someone give me a quick, complete fix for this?

like image 826
johnwargo Avatar asked Jul 08 '16 14:07

johnwargo


People also ask

How do I get a document from PyMongo?

To get all the Documents of the Collection use find() method. The find() method takes a query object as a parameter if we want to find all documents then pass none in the find() method.


1 Answers

It turns out Pymongo has a different format for sort. You can't pass in a JSON object, you have to use a dict. Once I fixed that, it all works:

cursor = mongo.db.measurements.find().sort([('timestamp', -1)]).limit(1)
like image 126
johnwargo Avatar answered Sep 24 '22 18:09

johnwargo