MongoDB get maximum value in Java | Java @ Desk
Home » » MongoDB get maximum value in Java

MongoDB get maximum value in Java



MongoDB get maximum value in Java

To get/find a maximum value from a collection in MongoDB is similar to getting a max value from a column in SQL.

Corresponding SQL query is similar to this

Select max(Column_Name) from Table_Name


Consider a collection called loan created as below

db.loan.insert( { _id: 10, item: "Personal Loans", interest: 14 } )
db.loan.insert( { _id: 10, item: "Home Loans", interest: 12 } )
db.loan.insert( { _id: 10, item: "Car Loans", interest: 16 } )


Let's find out the loan category having maximum interest rate among the three inserted in the collection above:

This example above has 3 interest rates 12 - Home Loans, 14 - Personal Loans, 16 - Car Loans

To get the maximum loan value use below query

db.loan.find().sort({interest: -1}).limit(1)


Java Example :

import java.net.UnknownHostException;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;

public class MongoDBFindMaximum {
 public static void main(String args[]) throws UnknownHostException {
  DB database = getDatabase();
  DBCollection collection = database.getCollection("loans");

  DBObject sort = new BasicDBObject();
  sort.put("interest", -1);
  
  DBCursor cursor = collection.find().sort(sort).limit(1);
  while (cursor.hasNext()) {
   System.out.println(cursor.next());
  }
 }

 public static DB getDatabase() throws UnknownHostException {
  Mongo mongo = new Mongo("localhost", 27017);
  DB database = mongo.getDB("yourdb");
  return database;
 }
}




0 comments:

Post a Comment