Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 421
Robin Avatar asked Apr 17 '18 06:04

Robin


People also ask

How do I fetch recent records in MongoDB?

MongoDB find() method is used to select documents from a specified collection. It also set the cursor position to the selected document. The default find() method gets the documents from the start of the collection.

What does PyMongo find_One return?

The find_One() method of pymongo is used to retrieve a single document based on your query, in case of no matches this method returns nothing and if you doesn't use any query it returns the first document of the collection.

How do I get data from PyMongo?

To select data from a table in MongoDB, we can also use the find() method. The find() method returns all occurrences in the selection. The first parameter of the find() method is a query object. In this example we use an empty query object, which selects all documents in the collection.


1 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.

like image 162
Neil Lunn Avatar answered Sep 19 '22 04:09

Neil Lunn