简体   繁体   English

使用pymongo的字段选择的mongodb的最后一条记录

[英]Last record of mongodb selected by a field with pymongo

I have a mongo collection with the fields: _id, id_station and last_date_tx (this it is a datetime).我有一个包含字段的 mongo 集合:_id、id_station 和 last_date_tx(这是一个日期时间)。 I need to extract the last _id according an assigned id_station.我需要根据分配的 id_station 提取最后一个 _id。 This code:这段代码:

tx = collectiondate.find({'id_station': "2052"}, {'_id': -1}).limit(1)
print(tx)

for pp in tx:
   print(tx)
   datetime_tx = pp['last_date_tx']
print(datetime_tx)

it produces the error:它产生错误:

<pymongo.cursor.Cursor object at 0x0000026841E64970>
{'_id': ObjectId('60fad1f65f26c6c04b59bd98')}
---------------------------------------------------------------------------
KeyError                                  
Traceback (most recent call last)
<ipython-input-33-86c8682bca23> in <module>
  4 for pp in pippo:
  5     print(pp)
----> 6     datetime_tx = pp['last_date_tx']
  7 print(datetime_tx)

KeyError: 'last_date_tx'

Any solution found doesn't solve my problem.找到的任何解决方案都不能解决我的问题。 Thanks for your help.谢谢你的帮助。

您可以使用find_one并以这种方式sort

tx = collectiondate.find_one({'id_station': "2052"}, sort=[( 'last_date_tx', pymongo.DESCENDING )])

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

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