Tuesday, 9 April 2019

Get results of request with sort and limit using pymongo

Let's take this simple collection col with 2 documents:

{
    "_id" : ObjectId("5ca4bf475e7a8e4881ef9dd2"),
    "timestamp" : 1551736800,
    "score" : 10
}
{
    "_id" : ObjectId("5ca4bf475e7a8e4881ef9dd3"),
    "timestamp" : 1551737400,
    "score" : 12
}

To access the last timestamp (the one of the second document), I first did this request

a = db['col'].find({}).sort("_id", -1)

and then a[0]['timestamp']

But as there will be a lot of documents in this collection, i think that it would be more efficient to request only the last one with the limit function, like

a = db['col'].find({}).sort("_id", -1).limit(1)

and then

for doc in a:
    lastTimestamp = doc['timestamp']

as there will be only one, i can declare the variable inside the loop.

So three questions :

  • Do i have to worry about memory / speed issues if i continue to use the first request and get the first element in the dic ?
  • Is there a smarter way to access the first element of the cursor instead of using a loop, when using the limit request ?
  • Is there another way to get that timestamp that i don't know ?

Thanks ! Python 3.6 / Pymongo 3.7



from Get results of request with sort and limit using pymongo

No comments:

Post a Comment