snippetpythonModerate
How to get minimum value in pyMongo
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:
but not one for getting the min. Is there a way to do this?
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:
This example assumes that:
To ensure your sort is based on documents that actually have a
For more information on sorting see:
# Sort by myfield (ascending value) and return first document
collection.find_one(sort=[("myfield", 1)])["myfield"]This example assumes that:
myfieldis a numeric value (so the sort order makes sense to determine a minimum or maximum)
myfieldexists in the matching document returned (otherwise Python will report aKeyErrorwhen trying to reference a non-existent field).
- all documents in the collection have a
myfieldvalue (documents that have do not have amyfieldvalue 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.