MongooseJS - How to find the element with the maximum value?

mongoose find
mongodb find document with max value
mongoose cursor
mongoose regex
mongodb find max value in array
mongoose skip
mongoose find sort
mongoose where condition

I am using MongoDB , MongooseJS and Nodejs.

I have a Collection ( called Member ) with the following Fields -

Country_id , Member_id , Name, Score

I want to write a query which returns the Member with the max Score where Country id = 10

I couldnt find suitable documentation for this in MongooseJS.

I found this at StackOVerflow ( this is MongoDB code )

Model.findOne({ field1 : 1 }).sort(last_mod, 1).run( function(err, doc) {
     var max = doc.last_mod;

But how do I translate the same to MongooseJS ?

  .findOne({ country_id: 10 })
  .sort('-score')  // give me the max
  .exec(function (err, member) {

    // your callback code


Check the mongoose docs for querying, they are pretty good.

If you dont't want to write the same code again you could also add a static method to your Member model like this:

memberSchema.statics.findMax = function (callback) {

  this.findOne({ country_id: 10 }) // 'this' now refers to the Member class

And call it later via Member.findMax(callback)

get max value in mongoose - node.js - html, findOne({ country_id: 10 }) .sort('-score') // give me the max .exec(function (err, member) { // your callback code }); Check the mongoose docs for querying, they  MongooseJS-How to find the element with the maximum value? (3) I am using MongoDB , MongooseJS and Nodejs.

You do not need Mongoose documentation to do this. Plain MongoDb will do the job.

Assume you have your Member collection:

{ "_id" : ObjectId("527619d6e964aa5d2bdca6e2"), "country_id" : 10, "name" : "tes2t", "score" : 15 }
{ "_id" : ObjectId("527619cfe964aa5d2bdca6e1"), "country_id" : 10, "name" : "test", "score" : 5 }
{ "_id" : ObjectId("527619e1e964aa5d2bdca6e3"), "country_id" : 10, "name" : "tes5t", "score" : -6 }
{ "_id" : ObjectId("527619e1e964aa5d2bdcd6f3"), "country_id" : 8, "name" : "tes5t", "score" : 24 }

The following query will return you a cursor to the document, you are looking for:

 db.Member.find({country_id : 10}).sort({score : -1}).limit(1)

Mongoose v5.9.20: Queries, how to get maximum value in mongoose query . in SQL it is easy SELECT So in reply to the module caller, remove this first element off the array (and make  How to get the data associated with the maximum id in a MySQL table? Getting the maximum value from a varchar field in MySQL; Finding the minimum and maximum value from a string with numbers separated by hyphen in MySQL? Limiting numbers to a maximum value in MySQL? How to find maximum value in an array using spread operator in JavaScript?

It might be faster to use find() than findOne().

With find().limit(1) an array of the one document is returned. To get the document object, you have to do get the first array element, maxResult[0].

Making Salvador's answer more complete ...

var findQuery = db.Member.find({country_id : 10}).sort({score : -1}).limit(1);

findQuery.exec(function(err, maxResult){
    if (err) {return err;}

    // do stuff with maxResult[0]


$max (aggregation), I am using MongoDB , MongooseJS and Nodejs. I have a Collection ( called Member ) with the following Fields –. Country_id , Member_id  max: Number, creates a validator that checks if the value is less than or equal to the given maximum. enum : Array, creates a validator that checks if the value is strictly equal to one of the values in the given array.

This is quick and easy using the Mongoose Query Helpers.

The general form for this could be:

   .exec( (error,data) => someFunc(error,data) {...} );

tldr: This will give you an array of a single item with the highest value in 'field_to_sort_by'. Don't forget to access it as data[0], like I did for an hour.

Long-winded: Step-by-step on what that string of functions is doing...

Your_Model.find() starts the query, no args needed.

.sort("-field_to_sort_by") sorts the everything in descending order. That minus-sign in front of the field name specifies to sort in descending order, you can discard it to sort in ascending order and thus get the document with the minimum value.

.limit(1) tells the database to only return the first document, because we only want the top-ranked document.

.exec( (error,data) => someFunc(error,data) {...} ) finally passes any error and an array containing your document to into your function. You'll find your document in data[0]

How to Use the Mongoose Limit Function, The JSON document's syntax is the same as the MongoDB shell. var Person = mongoose.model('Person', yourSchema); // find each person with a last name matching where('age').gt(17).lt(66). where('likes').in(['vaporizing', 'talking']). limit​(10). That means you're responsible for ensuring the values you pass in to an  Output: Maximum AND Value = 4 Better Approach : Idea is based on properties of AND operator. AND operation of any two bits result in 1 iff both bits are 1. We start from the MSB and check whether we have minimum of two elements of array having set value.

You can also use the $max operator:

// find the max age of all users
    { $group: { _id: null, maxAge: { $max: '$age' }}}
  , { $project: { _id: 0, maxAge: 1 }}
  , function (err, res) {
  if (err) return handleError(err);
  console.log(res); // [ { maxAge: 98 } ]

get max value in mongoose, $max compares both value and type, using the specified BSON comparison order for In MongoDB 3.2 and earlier, $max is available in the $group stage only. the array to operate on the numerical elements of the array to return a single value. The following example uses the $max in the $project stage to calculate the  Mongoose queries are not promises. They have a .then() function for co and async/await as a convenience. However, unlike promises, calling a query's .then() can execute the query multiple times.

Get maximum and minimum value in MongoDB?, For situations, mongoose provides the limit() function that can limit the We will perform the find() operation with the limit() function on the In the details collection, there are four documents where the value of the name field is “John”. Filter Array Elements in MongoDB · Delete MongoDB Document · Add  Given a singly linked list of n nodes and find the smallest and largest elements in linked list. Examples: Input : 15 14 13 22 17 Output : Linked list are: 17 -> 22 -> 13 -> 14 -> 15 -> NULL Maximum element in linked list: 22 Minimum element in linked list: 13 Input : 20 25 23 68 54 13 45 Output : Linked list are: 45 -> 13 -> 54 -> 68 -> 23 -> 25 -> 20 -> NULL Maximum element in linked list

How to get element with max id in MongoDB?, how to get maximum value in mongoose query . in SQL it is easy Retrieve only the queried element in an object array in MongoDB collection  The find and findOne functions both accept an object as input allowing for complex searches, whereas findById accepts just a single value with a callback function (an example will follow shortly). In this next example, I am going to demonstrate how to find all books that contain the string "mvc" in their title.

Use $max and $min operator along with aggregate framework to get the maximum and minimum value. Let us first create a collection with  The following operation returns documents in the bios collection where the embedded document name contains a field first with the value "Yukihiro" and a field last with the value "Matsumoto". The query uses dot notation to access fields in an embedded document: