I have a collection with several fields, and I'd like to get the minimum value from one. I know a command for getting the max value:
collection.find_one(sort=[("myfield", -1)])["myfield"]
but not one for getting the min. Is there a way to do this?
Best Answer
You can reverse the sort direction to get the minimum instead of the maximum value:
This example assumes that:
myfield
is a numeric value (so the sort order makes sense to determine a minimum or maximum)myfield
exists in the matching document returned (otherwise Python will report aKeyError
when trying to reference a non-existent field).myfield
value (documents that have do not have amyfield
value will sorted before the minimum numeric values)To ensure your sort is based on documents that actually have a
myfield
value you can add$exists
to the query criteria:For more information on sorting see: