HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonModerate

How to get minimum value in pyMongo

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
pymongominimumvaluegethow

Problem

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?

Solution

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:

  • Use Indexes to Sort Query Results



  • What is the compare order for BSON types?

Code Snippets

# Sort by myfield (ascending value) and return first document
 collection.find_one(sort=[("myfield", 1)])["myfield"]
collection.find_one({"myfield": {"$exists": True}}, sort=[("myfield", 1)])["myfield"]

Context

StackExchange Database Administrators Q#108113, answer score: 11

Revisions (0)

No revisions yet.