How fetch latest records using find_one in pymongo

Question:

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.

enter image description here

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

Asked By: Robin

||

Answers:

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.

Answered By: Neil Lunn

Another solution for obtaining the last record:

report = securitydb.scout.find_one({'aws_account_id':aws_account.account_number},
                                   sort=[('$natural', -1)])
Answered By: Evgen
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.