Syntax error How to find minimum value in MongoDB?

How to find minimum value in MongoDB?



To find the minimum value in MongoDB, you can use sort() along with limit(1). The syntax is as follows −

db.yourCollectionName.find().sort({yourFieldName: 1}).limit(1);

To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.findMinValueDemo.insertOne({"StudentMarks":78});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8f80ea2f684a30fbdfd59f")
}
> db.findMinValueDemo.insertOne({"StudentMarks":69});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8f80f02f684a30fbdfd5a0")
}
> db.findMinValueDemo.insertOne({"StudentMarks":79});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8f80f32f684a30fbdfd5a1")
}
> db.findMinValueDemo.insertOne({"StudentMarks":59});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8f80f82f684a30fbdfd5a2")
}
> db.findMinValueDemo.insertOne({"StudentMarks":91});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8f80fb2f684a30fbdfd5a3")
}

Display all documents from a collection with the help of find() method. The query is as follows −

> db.findMinValueDemo.find().pretty();

The following is the output −

{ "_id" : ObjectId("5c8f80ea2f684a30fbdfd59f"), "StudentMarks" : 78 }
{ "_id" : ObjectId("5c8f80f02f684a30fbdfd5a0"), "StudentMarks" : 69 }
{ "_id" : ObjectId("5c8f80f32f684a30fbdfd5a1"), "StudentMarks" : 79 }
{ "_id" : ObjectId("5c8f80f82f684a30fbdfd5a2"), "StudentMarks" : 59 }
{ "_id" : ObjectId("5c8f80fb2f684a30fbdfd5a3"), "StudentMarks" : 91 }

Here is the query to find the minimum value in MongoDB −

> db.findMinValueDemo.find().sort({StudentMarks: 1}).limit(1);

The following is the output −

{ "_id" : ObjectId("5c8f80f82f684a30fbdfd5a2"), "StudentMarks" : 59 }
Updated on: 2019-07-30T22:30:25+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements