How fetch latest records using find_one in pymongo

拜拜、爱过 提交于 2019-12-10 19:05:33

问题


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.

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.

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.

Thanks In Advance, Robin


回答1:


Use sort in the *args for 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.

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.



来源:https://stackoverflow.com/questions/49871030/how-fetch-latest-records-using-find-one-in-pymongo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!