问题描述
我有一个现有程序,试图在pymongo中使用find_one
提取与键aws_account_id
匹配的最后一个插入文档.
I have an existing program where I'm trying to fetch last inserted document which matches the key aws_account_id
using find_one
in pymongo.
我正在使用此查询来执行抓取操作:
I'm using this query to perform the fetching:
report = securitydb.scout.find_one({'aws_account_id': aws_account.account_number})
但是此查询返回了错误的文档.下图显示了预期的结果以及我得到的错误结果.
But this query returns a wrong document. The image below demonstrates the expected result and the wrong one that I'm getting.
在图像中,两个文档具有相同的aws_account_id,但是最后插入红色的.因此,预期结果是带有红色标记的文档,但它拉出了带有黄色标记的文档.
In the image, both documents have the same aws_account_id but the red one is inserted last. So the expected result is the red marked document but it pulls the yellow marked document.
我不确定是否需要使用排序或类似方法.我得到了一些解决方案,但是这些解决方案是基于纯mongo查询的.我需要在pymongo上执行此操作.
I'm not sure if I need to use sorting or things like that. I got some solution but those are based on pure mongo query. I need help doing this with pymongo.
在此先感谢您,罗宾
推荐答案
在*args
中将sort
用于 find_one()
Use sort
in the *args
for find_one()
report = securitydb.scout.find_one(
{'aws_account_id': aws_account.account_number},
sort=[( '_id', pymongo.DESCENDING )]
)
在这里使用_id
是因为ObjectId
值在添加时始终会增加",但是只要能将ObjectId
值包含在日期"中,它也可以表示最新". DESCENDING
排序顺序,表示最新"位于结果的顶部".
Using _id
here because the ObjectId
values are always going to "increase" as they are added, but anything else like a "date" which also indicates the "latest" can be used as long as it's in the DESCENDING
sort order, which means "latest" is on the "top" of the results.
如果尚未执行import pymongo
,则可以使用pymongo.DESCENDING
令牌,也可以使用-1
来指示降序".前者可能使代码更清晰.
You can import pymongo
if you didn't already do that and use the pymongo.DESCENDING
token, or just -1
to indicate "descending" order. The former probably makes much clearer code.
还要注意排序的字典",因为排序"的键的顺序通常很重要,或者至少在您要对多个键的组合进行排序的情况下如此.
Also note the "ordered dict" since the order of keys for "sorting" is usually important, or at least if you want to sort on the combination of more than one key.
这篇关于如何在pymongo中使用find_one获取最新记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!