get max value in mongoose


Question

how to get maximum value in mongoose query . in SQL it is easy

SELECT MAX(LAST_MOD) FROM table1
Where field1=1

i want Equivalent of above SQL code in mongoose(node.js)

1
9
5/13/2012 2:48:58 PM

Accepted Answer

MongoDB supports max/min, but they don't recommend using it in real applications :

min and max exist primarily to support the mongos (sharding) process.

http://www.mongodb.org/display/DOCS/min+and+max+Query+Specifiers

You could pretty much have the same result with :

Model.findOne({ field1 : 1 }).sort(last_mod, 1).run( function(err, doc) {
     var max = doc.last_mod;
});
7
5/13/2012 4:28:30 PM

I couldn't get the other answers to work. Perhaps I'm using a newer version of Mongoose (mongoose@3.0.1).

This worked for me:

Table1.findOne()
    .where({field1: 1})
    .sort('-LAST_MOD')
    .exec(function(err, doc)
    {
        var max = doc.LAST_MOD;
        // ...
    }
);

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon