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.

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

1 answer

  • answered 2018-04-17 06:39 Neil Lunn

    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.