且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在pymongo中使用find_one获取最新记录

更新时间:2022-12-05 17:21:10

*args中将sort用于

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.