简体   繁体   中英

Get latest Document with respect to (time or Id) using Pymongo only

In MongoDB, this technique is commonly used to obtain the latest document with respect to (time or ID):

 db.collection.find().sort({ "_id": -1 }).limit(1);

 MySchema.find().sort({ _id: -1 }).limit(1)

db.getLastInsertedDocument.find({}).sort({_id:-1}).limit(1);

But when I use pymongo to find the latest entry in my collection the code below gives an error.

from pymongo import MongoClient

import random
import datetime
import time
import pprint
from datetime import datetime
#from bson import ObjectId

client = MongoClient()
client = MongoClient('localhost', 27017)
db = client.sensor_temperature # createdb
posts = db.posts2
print('Total Record for the collection: ' + str(posts.count()))

x=datetime.now().strftime("%H:%M:%S")

record=posts.find().sort({ "_id": -1 }).limit(1)  ###  ERR
#record=posts.find({"start_date":new Date()}).pretty() ####  ERR
#record=posts.findOne({"_id": x}) #### <pymongo.cursor.Cursor object at 0x0141FCD0>
pprint.pprint(record)
text=record
print(text)

How to get the latest records using Pymongo only?

Some of the pymongo driver commands don't match exactly to the mongodb shell. The documentation explains the method calls. This should work:

from pymongo import MongoClient, DESCENDING
<...>
record=posts.find().sort('_id', DESCENDING).limit(1)
pprint.pprint(list(record)[0])

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