Currently, this is my code in order to find the most recent document in my mongodb database
async def _last_bump_time(self):
last_bump = bump_db.find().limit(1).sort('$natural', ASCENDING).limit(1)
last_bump = last_bump["date"]
return datetime.strptime(last_bump,"%S:%M:%H:%d:%m:%Y")
but it is giving me an error, TypeError: index 'date' cannot be applied to Cursor instances
What is the best way to find the most react document, and be able to retrieve the data from the document without having the document to have an extra parameter?
'
My document is ordered like this with three parameters
_id:6292a0d4cc2ef69845749028
id:736933464292589568
date:"16:23:20:28:05:2022"
CodePudding user response:
You're using find
which is intended to retrieve multiple documents. It returns a Cursor, which lets you go through the returned documents one-by-one.
You could instead use find_one
, which will return a single document or None
. find_one
also supports passing a sort
parameter, expecting a list of (key, direction) pairs specifying the sort order. Put all together, it could look like this:
async def _last_bump_time(self):
last_bump = bump_db.find_one(sort=[('$natural', ASCENDING)])
# last_bump is None if your database is empty.
if last_bump:
return datetime.strptime(last_bump["date"],"%S:%M:%H:%d:%m:%Y")
return datetime.now() # Example return value in the case of an empty database. Feel free to update.