简体   繁体   中英

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

If you are using any field with an unique index in the selection criteria, you should use find_one method which will return the only document that matches your query.

That being said, the find method returns a Cursor object and does not load the data into memory.

You might get a better performance if you where using a filter option. Your query as it is now will do a collection scan.

if you are not using a filter, and want to retrieve the last document, then the clean way is with the Python built-in next function. You could also use the next method.

cur = db["col"].find().sort({"_id": -1}).limit(1):
with cur:
    doc = next(cur, None) # None when we have empty collection.

find()。sort()是如此之快,不必担心速度,它是访问游标第一个元素的最佳途径。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM