Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find min value in mongodb

How do you do the equivalent of

SELECT    MIN(Id) AS MinId FROM   Table 

with MongoDB?

It looks like I will have to use MapReduce but I can't find any example that shows how to do this.

like image 983
atbebtg Avatar asked Jun 15 '11 15:06

atbebtg


People also ask

How does MongoDB calculate minimum?

You can also use min function like this. $min is an accumulator operator available only in the $group stage. UPDATE: Changed in version 3.2: $min is available in the $group and $project stages. In previous versions of MongoDB, $min is available in the $group stage only.

How does MongoDB calculate min max?

You need to use the . aggregate() method for it to work. For very large collections aggregating pipeline can be very slow because it scans each document. The solution mentioned here can be better if you need to find min/max of the indexed field: stackoverflow.com/a/6360583/3438640 Use find with sort and limit: db.

What is $first in MongoDB?

This means $first returns the first order type for the documents between the beginning of the partition and the current document.

What is ISODate in MongoDB?

You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats: new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.


1 Answers

You can use a combination of sort and limit to emulate min:

> db.foo.insert({a: 1}) > db.foo.insert({a: 2}) > db.foo.insert({a: 3}) > db.foo.find().sort({a: 1}).limit(1)  { "_id" : ObjectId("4df8d4a5957c623adae2ab7e"), "a" : 1 } 

sort({a: 1}) is an ascending (minimum-first) sort on the a field, and we then only return the first document, which will be the minimum value for that field.

EDIT: note that this is written in the mongo shell, but you can do the same thing from C# or any other language using the appropriate driver methods.

like image 98
dcrosta Avatar answered Sep 29 '22 19:09

dcrosta