8

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?

1 Answer 1

11

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:

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.