If looking for the minimum value for a field in MongoDB, use this command:

db.collection_name.find({"field_name": {$ne: null}}).sort({"field_name":1}).limit(1)


This command finds all documents in the collection that have the field you care about, sorts them in ascending order, and returns the first one i.e. the minumum.

The purpose of having the find method with an argument of {"field_name": {$ne: null}} is that this filters out all the documents that don’t contain the field you’re interested in. If you don’t include the find argument (that is, do db.collection_name.find()...) and you have a document in the collection that doesn’t contain the field (yay schema less databases), then that will mess up your query because of the way Mongo handles null fields. Hence, we filter out all documents not containing the field, using the $ne operator.

The sort method takes in either 1 or -1 to define ascending or descending respectively. For the minimum case, we want to use 1.

The limit method specifies the number of documents to return. In our case, we only want the first one in the sorted set, so we supply 1.

Similarly, to get the maximum value for a field, use

db.collection_name.find({"field_name": {$ne: null}}).sort({"field_name":-1}).limit(1)

None of the commands I found on the interwebz had this filtering on the null fields, and that was messing up my query.