[英]How fetch latest records using find_one in pymongo
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. 我有一个现有的程序,我正在尝试使用
find_one
中的find_one来获取最后插入的文档,该文档与密钥aws_account_id
匹配。
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.
下图显示了我得到的预期结果和错误的结果。
In the image, both documents have the same aws_account_id but the red one is inserted last. 在图像中,两个文档都具有相同的aws_account_id,但最后插入了红色文档。 So the expected result is the red marked document but it pulls the yellow marked document.
所以预期的结果是红色标记的文件,但它拉出黄色标记的文件。
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.
我得到了一些解决方案,但这些都是基于纯mongo查询。 I need help doing this with pymongo.
我需要帮助用pymongo这样做。
Thanks In Advance, Robin 谢谢提前,罗宾
Use sort
in the *args
for find_one()
在
*args
使用sort
为find_one()
report = securitydb.scout.find_one(
{'aws_account_id': aws_account.account_number},
sort=[( '_id', pymongo.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. 在这里使用
_id
是因为ObjectId
值在添加时总是会“增加”,但是只要它处于DESCENDING
排序顺序,就可以使用任何其他类似“日期”的东西,它也表示“最新”,这意味着“最新的“在结果的”顶部“。
You can import pymongo
if you didn't already do that and use the pymongo.DESCENDING
token, or just -1
to indicate "descending" order. 如果您还没有这样做,可以
import pymongo
并使用pymongo.DESCENDING
标记,或者只使用-1
表示“降序”顺序。 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. 另请注意“有序字典”,因为“排序”键的顺序通常很重要,或者至少如果要对多个键的组合进行排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.