简体   繁体   English

仅使用 Pymongo 获取关于(时间或 ID)的最新文档

[英]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):在 MongoDB 中,该技术通常用于获取关于(时间或 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.但是当我使用 pymongo 在我的集合中查找最新条目时,下面的代码会出错。

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?如何仅使用 Pymongo 获取最新记录?

Some of the pymongo driver commands don't match exactly to the mongodb shell.某些 pymongo 驱动程序命令与 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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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