Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find minimum value on mongodb

I am trying to find out the student scored the minimum mark on the collection. I am not getting expected output. Your help would be appreciated:

    > db.Student.find()
    { "_id" : ObjectId("5c8a3e85e8e2bcb1a75780c4"), "Name" : "Nandhi", "Mark" : 90 }
    { "_id" : ObjectId("5c8a3e85e8e2bcb1a75780c5"), "Name" : "Rajan", "Mark" : 80 }
    { "_id" : ObjectId("5c8a3e85e8e2bcb1a75780c6"), "Name" : "Raj", "Mark" : 75 }

Query:

    > db.Student.aggregate([{$group:{_id:"Mark",avg_marks:{$min:1}}}])

Output

    { "_id" : "Mark", "avg_marks" : 1 }
like image 958
Nandy Avatar asked Nov 26 '25 02:11

Nandy


1 Answers

Sort by mark and limit to 1

db.Student.find().sort({Mark:1}).limit(1)

Using aggregation

db.Student.aggregate(
[
 {
   $group:
     {
       _id: null,
       minMark: { $min: "$Mark" }
     }
 }
])
like image 181
Ashwanth Madhav Avatar answered Nov 27 '25 15:11

Ashwanth Madhav



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!