Search code examples
javascriptmongodbmapreducemongodb-querymongoid

How to find longest and shortest length of a value for a field in mongoDb?


The data type of the field is String. I would like to find the length of the longest and shortest value for a field in mongoDB.

I have totally 500000 documents in my collection.


Solution

  • You can use a mongo shell script. Note that it will perform a full table scan.

        function findMinMax() {
            var max = 0;
            var min = db.collection.findOne().fieldName.length;
    
            db.collection.find().forEach(function(doc) {
                var currentLength = doc.fieldName.length; 
                if (currentLength > max) {
                   max = currentLength;
                }
                if (currentLength < min) {
                   min = currentLength;
                }
            });
    
             print(max);
             print(min);
        }
    
       use <databaseName>
       findMinMax();
    

    You can save the function in a file say c:\minMax.js and run the file as,

    c:\mongodb\bin> mongo dbName < c:\minMax.js
    

    Note: you may need to supply the necessary hostname, user name, password to connect to your database.

    c:\mongodb\bin> mongo --host hostName --port portNumber -u userName -p password dbName < c:\minMax.js