Finding the Min and Max values in MongoDB

In MongoDB, the min() and max() functions work as limitors – essentially the same as “gte” (>=) and “lt” (<).

To find the highest (maximum) value in MongoDB, you can use this command;

db.thiscollection.find().sort({"thisfieldname":-1}).limit(1)

This essentially sorts the data by the fieldname in decending and takes the first value.

The lowest (minimum) value can be determined in a similar way.

db.thiscollection.find().sort({"thisfieldname":1}).limit(1)

Note that if the dataset is large and the field is not indexed, this could take a long time.

If you want to find the max using a “group by” equivalent, you need to use map-reduce.

db.thiscollection.group(  s
    {key: {name:true},
        reduce: function(obj, prev) {
            if (prev.maxValue < obj.thisfieldname) {
                prev.maxValue = obj.thisfieldname;
            }
        },
    initial: { maxValue: 0 }}
);

Leave a comment

Your email address will not be published. Required fields are marked *