You can reverse the sort direction to get the minimum instead of the maximum value:
# Sort by myfield (ascending value) and return first document
collection.find_one(sort=[("myfield", 1)])["myfield"]
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 a KeyError
when trying to reference a non-existent field).
- all documents in the collection have a
myfield
value (documents that have do not have a myfield
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:
collection.find_one({"myfield": {"$exists": True}}, sort=[("myfield", 1)])["myfield"]
For more information on sorting see: