Nandy
Nandy

Reputation: 696

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 }

Upvotes: 3

Views: 2412

Answers (2)

Ashwanth Madhav
Ashwanth Madhav

Reputation: 1134

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" }
     }
 }
])

Upvotes: 4

Serkan Arslan
Serkan Arslan

Reputation: 13403

You can use sort and limit

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

Upvotes: 2

Related Questions