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.
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.
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.
This means $first returns the first order type for the documents between the beginning of the partition and the current document.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With