Search code examples
python-3.xflaskpymongoeve

How to use lookup filters to sort results in PythonEve using PyMongo


In PythonEve using MongoDB, how can I get (internally) the last item created in a given collection?

Looking into eve's mongo module find_one_raw looks like the way to go. I am trying something like the following without success:

last = app.data.find_one_raw('aresource',**{"_created": {"sort": 1}})


Solution

  • The pymongo driver accepts fairly standard mongo syntax, try the following:

    collection = app.data.driver.db['collection']
    
    last = collection.find().sort([('_created', -1)]).limit(1)
    

    This will sort the documents newest to oldest, and return a cursor with 1 result, that being the newest possible document.Getting the first element (last[0]) of the cursor returns a dictionary as intended.