Java & MongoDB - Quick Guide



Java & MongoDB - Overview

MongoDB developer team has provided MongoDB Driver for Java and have various resources available for it.

First step in connecting to MongoDB using Java is to have mongodb driver in the java classpath and then use mongodb API to connect to the database.

Connecting to MongoDB database

Suppose, MongoDB is installed locally and using default port then following syntax connects to MongoDB database.

MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");

As MongoClient assumes various default, it can be used using the following way as well.

MongoClient mongoClient = MongoClients.create();

Creating/Connecting to Database

Once mongoClient is instantiated, its getDatabase() method can be used to get connection to a database.

MongoDatabase database = mongoClient.getDatabase("myDb"); 

In case database is not present then above command will create the same.

In subsequent chapters, we'll see the various operations on MongoDB using Java.

Java & MongoDB - Environment Setup

Install MongoDB database

Follow the MongoDB installation steps using MongoDB - Environment

Install Java

Java SE can be downloaded for free from the following link −

https://www.oracle.com/technetwork/java/javase/downloads/index-jsp-138363.html

You download a version based on your operating system.

Follow the instructions to download Java, and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories.

Setting Up the Path for Windows 2000/XP

Assuming you have installed Java in c:\Program Files\java\jdk directory −

  • Right-click on 'My Computer' and select 'Properties'.

  • Click on the 'Environment variables' button under the 'Advanced' tab.

  • Now, alter the 'Path' variable so that it also contains the path to the Java executable. For example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.

Setting Up the Path for Windows 95/98/ME

Assuming you have installed Java in c:\Program Files\java\jdk directory −

  • Edit the 'C:\autoexec.bat' file and add the following line at the end −

    SET PATH=%PATH%;C:\Program Files\java\jdk\bin

Setting Up the Path for Linux, UNIX, Solaris, FreeBSD

Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this.

For example, if you use bash as your shell, then you would add the following line at the end of your '.bashrc: export PATH=/path/to/java:$PATH'

Popular Java Editors

To write Java programs, you need a text editor. There are even more sophisticated IDEs available in the market. But for now, you can consider one of the following −

  • Notepad − On Windows machine, you can use any simple text editor like Notepad (recommended for this tutorial) or TextPad.

  • Netbeans − It is a Java IDE that is open-source and free. It can be downloaded from https://netbeans.org/index.html.

  • Eclipse − It is also a Java IDE developed by the Eclipse open-source community and can be downloaded from www.eclipse.org/.

Java MongoDB Driver

  • You need to download the jar mongo-java-driver.jar. Make sure to download the latest release of these jar files.

  • You need to include the downloaded jar files into your classpath.

  • We are using mongo-java-driver-3.12.8.jar to run examples.

Java & MongoDB - Connecting Database

To connect database, you need to specify the database name, if the database doesn't exist then MongoDB creates it automatically.

MongoDatabase database = mongo.getDatabase("myDb");

Example

Following is the code snippet to connect to the database −

import com.mongodb.MongoCredential;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;

public class Tester {
   public static void main(String[] args) {
      // Creating a Mongo client 
      MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
      MongoDatabase database = mongo.getDatabase("myDb");

      // Creating Credentials 
      MongoCredential credential; 
      credential = MongoCredential.createCredential("sampleUser", "myDb", "password".toCharArray());

      System.out.println("Credentials ::"+ credential);  
   }
}

Now, let's compile and run the above program as shown below.

$javac Tester.java 
$java Tester

Output

On executing, the above program gives you the following output.

Credentials ::MongoCredential{mechanism=null, userName='sampleUser', source='myDb', password=<hidden>, mechanismProperties=<hidden>}

Java & MongoDB - Show Databases

To show databases, you can use MongoClient.listDatabaseNames() method to get the name of all the databases.

MongoIterable<String> list = mongoClient.listDatabaseNames();
for (String name : list) {
   System.out.println(name);
}

As we have created an empty database in Connect Database chapter, we need to insert a document to make it visible in mongodb database list.

Example

Following is the code snippet to list down database −

import org.bson.Document;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;

public class Tester {
   public static void main(String[] args) {
      // Creating a Mongo client 
      MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
      MongoDatabase database = mongoClient.getDatabase("myDb");
      database.createCollection("sampleCollection");

      // Retrieving a collection
      MongoCollection<Document> collection = database.getCollection("sampleCollection");
      Document document = new Document("title", "MongoDB")
         .append("description", "database")
         .append("likes", 100)
         .append("url", "http://www.tutorialspoint.com/mongodb/")
         .append("by", "tutorials point");

      //Inserting document into the collection
      collection.insertOne(document);

      MongoIterable<String> list = mongoClient.listDatabaseNames();
      for (String name : list) {
         System.out.println(name);
      }
   }
}

Now, let's compile and run the above program as shown below.

$javac Tester.java 
$java Tester

Output

On executing, the above program gives you the following output.

admin
config
local
myDb

Java & MongoDB - Drop Database

To drop a databases, you can use MongoDatabse.drop() method to drop the selected databases.

// Creating a Mongo client 
MongoClient mongoClient = MongoClients.create();

// connect the database	   
MongoDatabase database = mongoClient.getDatabase("myDb");

// drop the database
database.drop();

Example

Following is the code snippet to drop a database −

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;

public class Tester {
   public static void main(String[] args) {
      // Creating a Mongo client 
      MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
      MongoDatabase database = mongoClient.getDatabase("myDb");

      // drop the database
      database.drop();
      System.out.println("Database dropped.");
      
      // print the databases	   
      MongoIterable<String> list = mongoClient.listDatabaseNames();
      for (String name : list) {
         System.out.println(name);
      }
   }
}

Now, let's compile and run the above program as shown below.

$javac Tester.java 
$java Tester

Output

On executing, the above program gives you the following output.

Database dropped.
admin
config
local

Java & MongoDB - Create Collection

To drop a databases, you can use MongoDatabse.createCollection() method to create a collection in the databases.

// Creating a Mongo client 
MongoClient mongoClient = MongoClients.create();

// Connect the database	   
MongoDatabase database = mongoClient.getDatabase("myDb");

// Create the collection
database.createCollection("sampleCollection");

Example

Following is the code snippet to create a collection −

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;

public class Tester {
   public static void main(String[] args) {
      // Creating a Mongo client 
      MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");

      // Connect to database
      MongoDatabase database = mongoClient.getDatabase("myDb");

      // Create the collection
      database.createCollection("sampleCollection");
      System.out.println("Collection created.");
   }
}

Now, let's compile and run the above program as shown below.

$javac Tester.java 
$java Tester

Output

On executing, the above program gives you the following output.

Collection created.

Java & MongoDB - Drop Collection

To drop a databases, you can use collection.drop() method to drop a collection in the databases.

// Get the collection
MongoCollection<Document> collection = database.getCollection("sampleCollection");

// delete the collection
collection.drop();

Example

Following is the code snippet to drop a collection −

import org.bson.Document;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class Tester {
   public static void main(String[] args) {
      // Creating a Mongo client 
      MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");

      // get the database
      MongoDatabase database = mongoClient.getDatabase("myDb");

      // Retrieving a collection
      MongoCollection<Document> collection = database.getCollection("sampleCollection");

      collection.drop();
      System.out.println("Collection dropped.");
   }
}

Now, let's compile and run the above program as shown below.

$javac Tester.java 
$java Tester

Output

On executing, the above program gives you the following output.

Collection dropped.

Java & MongoDB - Display Collections

To display list of collections, you can use database.listCollectionNames() method to get the list of collection names in the databases.

MongoIterable<String> collections = database.listCollectionNames();

Example

Following is the code snippet to display list of collections −

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;

public class Tester {
   public static void main(String[] args) {
      // Creating a Mongo client 
      MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");

      // Get the database
      MongoDatabase database = mongoClient.getDatabase("myDb");

      // Create the collection
      database.createCollection("sampleCollection");

      // Get the list of collection names
      MongoIterable<String> collections = database.listCollectionNames();

      for (String name : collections) {
         System.out.println(name);
      }	   
   }
}

Now, let's compile and run the above program as shown below.

$javac Tester.java 
$java Tester

Output

On executing, the above program gives you the following output.

sampleCollection

Java & MongoDB - Insert Document

To insert a document in a collection, you can use collection.insertOne() or collection.insertMany() methods to insert documents in the collection.

// insert a single document
collection.insertOne(document);

// insert multiple documents
collection.insertMany(documents);

Example

Following is the code snippet to insert documents in a collection −

import java.util.ArrayList;
import java.util.List;

import org.bson.Document;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class Tester {
   public static void main(String[] args) {
      // Creating a Mongo client 
      MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
      MongoDatabase database = mongoClient.getDatabase("myDb");

      // Get the collection
      MongoCollection<Document> collection = database.getCollection("sampleCollection");

      Document document = new Document("First_Name", "Mahesh")
         .append("Last_Name", "Parashar")
         .append("Date_Of_Birth", "1990-08-21")
         .append("e_mail", "mahesh_parashar.123@gmail.com")
         .append("phone", "9034343345");

      collection.insertOne(document);
      List<Document> documents = new ArrayList<>();

      documents.add(new Document("First_Name", "Radhika")
         .append("Last_Name", "Sharma")
         .append("Date_Of_Birth", "1995-09-26")
         .append("e_mail", "radhika_sharma.123@gmail.com")
         .append("phone", "9000012345"));

      documents.add(new Document("First_Name", "Rachel")
         .append("Last_Name", "Christopher")
         .append("Date_Of_Birth", "1990-02-16")
         .append("e_mail", "Rachel_Christopher.123@gmail.com")
         .append("phone", "9000054321"));

      documents.add(new Document("First_Name", "Fathima")
         .append("Last_Name", "Sheik")
         .append("Date_Of_Birth", "1990-02-16")
         .append("e_mail", "Fathima_Sheik.123@gmail.com")
         .append("phone", "9000054321"));

      collection.insertMany(documents);

      System.out.println("Documents inserted.");
   }
}

Now, let's compile and run the above program as shown below.

$javac Tester.java 
$java Tester

Output

On executing, the above program gives you the following output.

Documents inserted.

Java & MongoDB - Select Document

To select a document in a collection, you can use collection.find() or collection.find(filter) methods to select documents of a collection.

// find all documents of a collection
collection.find();

// find document(s) fulfiling the filter criteria
collection.find(filter);

Example

Following is the code snippet to display selected documents −

import java.util.ArrayList;
import java.util.List;

import org.bson.Document;

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

public class Tester {
   public static void main(String[] args) {
      // Creating a Mongo client 
      MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
      MongoDatabase database = mongoClient.getDatabase("myDb");

      // Get the collection
      MongoCollection<Document> collection = database.getCollection("sampleCollection");

      // Find all documents
      FindIterable<Document> allDocuments = collection.find();

      for (Document document : allDocuments) {
         System.out.println(document);
      }
      System.out.println("***Selected Document***");
      
      // Select a particular document
      FindIterable<Document> documents = collection.find(Filters.eq("First_Name","Mahesh"));
      for (Document document : documents) {
         System.out.println(document);
      }
   }
}

Now, let's compile and run the above program as shown below.

$javac Tester.java 
$java Tester

Output

On executing, the above program gives you the following output.

Document{{_id=60b70d426214461f10ac5c99, First_Name=Mahesh, Last_Name=Parashar, Date_Of_Birth=1990-08-21, e_mail=mahesh_parashar.123@gmail.com, phone=9034343345}}
Document{{_id=60b70d426214461f10ac5c9a, First_Name=Radhika, Last_Name=Sharma, Date_Of_Birth=1995-09-26, e_mail=radhika_sharma.123@gmail.com, phone=9000012345}}
Document{{_id=60b70d426214461f10ac5c9b, First_Name=Rachel, Last_Name=Christopher, Date_Of_Birth=1990-02-16, e_mail=Rachel_Christopher.123@gmail.com, phone=9000054321}}
Document{{_id=60b70d426214461f10ac5c9c, First_Name=Fathima, Last_Name=Sheik, Date_Of_Birth=1990-02-16, e_mail=Fathima_Sheik.123@gmail.com, phone=9000054321}}
********
Document{{_id=60b70d426214461f10ac5c99, First_Name=Mahesh, Last_Name=Parashar, Date_Of_Birth=1990-08-21, e_mail=mahesh_parashar.123@gmail.com, phone=9034343345}}

Java & MongoDB - Update Document

To update a document in a collection, you can use collection.updateOne() method to update a particular document of a collection.

collection.updateOne(filter,update);

Example

Following is the code snippet to update and display updated document −

import java.util.ArrayList;
import java.util.List;

import org.bson.Document;

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;

public class Tester {
   public static void main(String[] args) {
      // Creating a Mongo client 
      MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
      MongoDatabase database = mongoClient.getDatabase("myDb");

      // Get the collection
      MongoCollection<Document> collection = database.getCollection("sampleCollection");

      // Find all documents
      collection.updateOne(Filters.eq("First_Name","Mahesh"),
      Updates.set("e_mail", "maheshparashar@gmail.com"));
      System.out.println("Document Updated.");
      System.out.println("***Updated Document***");
      
      // Select a particular document
      FindIterable<Document> documents = collection.find(Filters.eq("First_Name","Mahesh"));

      for (Document document : documents) {
         System.out.println(document);
      }
   }
}

Now, let's compile and run the above program as shown below.

$javac Tester.java 
$java Tester

Output

On executing, the above program gives you the following output.

Document Updated.
***Updated Document***
Document{{_id=60b70d426214461f10ac5c99, First_Name=Mahesh, Last_Name=Parashar, Date_Of_Birth=1990-08-21, e_mail=maheshparashar@gmail.com, phone=9034343345}}

Java & MongoDB - Delete Document

To delete a document in a collection, you can use collection.deleteOne() method to delete a particular document of a collection.

collection.deleteOne(filter);

Example

Following is the code snippet to delete a document and display remaining documents −

import org.bson.Document;

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

public class Tester {
   public static void main(String[] args) {
      // Creating a Mongo client 
      MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
      MongoDatabase database = mongoClient.getDatabase("myDb");

      // Get the collection
      MongoCollection<Document> collection = database.getCollection("sampleCollection");

      // Find all documents
      collection.deleteOne(Filters.eq("First_Name","Mahesh"));
      System.out.println("Document deleted.");
      System.out.println("***Documents***");
      
      // Select a particular document
      FindIterable<Document> documents = collection.find();

      for (Document document : documents) {
         System.out.println(document);
      }
   }
}

Now, let's compile and run the above program as shown below.

$javac Tester.java 
$java Tester

Output

On executing, the above program gives you the following output.

Document deleted.
***Documents***
Document{{_id=60b70d426214461f10ac5c9a, First_Name=Radhika, Last_Name=Sharma, Date_Of_Birth=1995-09-26, e_mail=radhika_sharma.123@gmail.com, phone=9000012345}}
Document{{_id=60b70d426214461f10ac5c9b, First_Name=Rachel, Last_Name=Christopher, Date_Of_Birth=1990-02-16, e_mail=Rachel_Christopher.123@gmail.com, phone=9000054321}}
Document{{_id=60b70d426214461f10ac5c9c, First_Name=Fathima, Last_Name=Sheik, Date_Of_Birth=1990-02-16, e_mail=Fathima_Sheik.123@gmail.com, phone=9000054321}}

Java & MongoDB - Embedded Documents

To insert a document with embedded document in a collection, you can use DBObject/BasicDBObject objects as shown below −

// Create an embedded document
BasicDBObject comment = new BasicDBObject();
comment.put("user", "User1");
comment.put("message", "My First Comment");
comment.put("dateCreated", "20/2/2020");
comment.put("like", "0");

// create an array
List<String> tags = new ArrayList<String>();
tags.add("mongodb");
tags.add("database");
tags.add("NoSQL");


// add array and embedded documents
Document document = new Document("title", "MongoDB Overview")
   .append("tags",tags)
   .append("comment", comment);

Example

Following is the code snippet to insert a document with embedded documents and display them −

import java.util.ArrayList;
import java.util.List;

import org.bson.Document;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

public class Tester {
   public static void main(String[] args) {
      // Creating a Mongo client 
      MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
      MongoDatabase database = mongoClient.getDatabase("myDb");

      // Create the collection
      database.createCollection("post");

      MongoCollection<Document> collection = database.getCollection("post");
      List<String> tags = new ArrayList<String>();
      tags.add("mongodb");
      tags.add("database");
      tags.add("NoSQL");

      BasicDBObject comment1 = new BasicDBObject();
      comment1.put("user", "User1");
      comment1.put("message", "My First Comment");
      comment1.put("dateCreated", "20/2/2020");
      comment1.put("like", "0");

      BasicDBObject comment2 = new BasicDBObject();
      comment2.put("user", "User2");
      comment2.put("message", "My Second Comment");
      comment2.put("dateCreated", "20/2/2020");
      comment2.put("like", "0");

      List<DBObject> comments = new ArrayList<DBObject>();
      comments.add(comment1);
      comments.add(comment2);

      Document document = new Document("title", "MongoDB Overview")
         .append("description", "MongoDB is no SQL database")
         .append("by", "tutorials point")
         .append("url", "http://www.tutorialspoint.com")
         .append("tags",tags)
         .append("comments", comments);

      collection.insertOne(document);

      FindIterable<Document> documents = collection.find(Filters.eq("title","MongoDB Overview"));

      for (Document doc : documents) {
         System.out.println(doc);
      }
   }
}

Now, let's compile and run the above program as shown below.

$javac Tester.java 
$java Tester

On executing, the above program gives you the following output.

Output

Document{{_id=60b7ab7614bd6b4a14b46d47, title=MongoDB Overview, 
   description=MongoDB is no SQL database, by=tutorials point, 
   url=http://www.tutorialspoint.com, tags=[mongodb, database, NoSQL], 
   comments=[Document{{user=User1, message=My First Comment, 
   dateCreated=20/2/2020, like=0}}, Document{{user=User2, message=My Second Comment, 
   dateCreated=20/2/2020, like=0}}]
}}

Java & MongoDB - Referenced Documents

To insert a document with referenced documents in a collection, you can use DBRef object as shown below −

// create a document
Document comment1 = new Document();
comment1.put("_id", "comment1");
comment1.put("user", "User1");
comment1.put("message", "My First Comment");
comment1.put("dateCreated", "20/2/2020");
comment1.put("like", "0");

// create a database reference
DBRef comment1Ref = new DBRef("post", comment1.get("_id"));

// insert the reference in the document
Document document = new Document("title", "Java Overview")
.append("comment1", comment1Ref);

Example

Following is the code snippet to insert a document with referenced documents and display them −

import java.util.ArrayList;
import java.util.List;

import org.bson.Document;

import com.mongodb.DBRef;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

public class Tester {
   public static void main(String[] args) {
      // Creating a Mongo client 
      MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
      MongoDatabase database = mongoClient.getDatabase("myDb");
      MongoCollection<Document> collection = database.getCollection("post");
      List<String> tags = new ArrayList<String>();
      tags.add("mongodb");
      tags.add("database");
      tags.add("NoSQL");

      Document comment1 = new Document();
      comment1.put("_id", "comment1");
      comment1.put("user", "User1");
      comment1.put("message", "My First Comment");
      comment1.put("dateCreated", "20/2/2020");
      comment1.put("like", "0");

      DBRef comment1Ref = new DBRef("post", comment1.get("_id"));

      Document comment2 = new Document();
      comment2.put("_id", "comment2");
      comment2.put("user", "User2");
      comment2.put("message", "My Second Comment");
      comment2.put("dateCreated", "20/2/2020");
      comment2.put("like", "0");

      DBRef comment2Ref = new DBRef("post", comment2.get("_id"));

      List<Document> comments = new ArrayList<Document>();
      comments.add(comment1);
      comments.add(comment2);

      Document document = new Document("title", "Java Overview")
         .append("description", "Java is programming language")
         .append("by", "tutorials point")
         .append("url", "http://www.tutorialspoint.com")
         .append("tags",tags)
         .append("comment1", comment1Ref)
         .append("comment2", comment2Ref);

      collection.insertMany(comments);
      collection.insertOne(document);

      FindIterable<Document> documents = collection.find(Filters.eq("title","Java Overview"));

      for (Document doc : documents) {
         System.out.println(doc);
      }
   }
}

Now, let's compile and run the above program as shown below.

$javac Tester.java 
$java Tester

Output

On executing, the above program gives you the following output.

Document{{_id=60b7b26b7671f469993fdc3c, title=Java Overview, 
   description=Java is programming language, by=tutorials point, 
   url=http://www.tutorialspoint.com, tags=[mongodb, database, NoSQL], 
   comment1={ "$ref" : "post", "$id" : "comment1" }, comment2={ "$ref" : "post", "$id" : "comment2" }
}}

Java & MongoDB - Limiting Documents

To select a given number of document in a collection, you can use collection.find().limit() methods to select required no. of documents of a collection.

int n = 2;

// find required documents of a collection
collection.find().limit(n);

Example

Following is the code snippet to display limited documents −

import org.bson.Document;

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class Tester {
   public static void main(String[] args) {
      // Creating a Mongo client 
      MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
      MongoDatabase database = mongoClient.getDatabase("myDb");

      // Get the collection
      MongoCollection<Document> collection = database.getCollection("sampleCollection");

      // Find two documents
      FindIterable<Document> allDocuments = collection.find().limit(2);

      for (Document document : allDocuments) {
         System.out.println(document);
      }
   }
}

Now, let's compile and run the above program as shown below.

$javac Tester.java 
$java Tester

Output

On executing, the above program gives you the following output.

Document{{_id=60b70d426214461f10ac5c9a, First_Name=Radhika, Last_Name=Sharma, Date_Of_Birth=1995-09-26, e_mail=radhika_sharma.123@gmail.com, phone=9000012345}}
Document{{_id=60b70d426214461f10ac5c9b, First_Name=Rachel, Last_Name=Christopher, Date_Of_Birth=1990-02-16, e_mail=Rachel_Christopher.123@gmail.com, phone=9000054321}}

Java & MongoDB - Sorting Documents

To get sorted document in a collection, you can use collection.find().sort() methods to select sorted documents of a collection.

// find sorted documents of a collection
collection.find().sort(new BasicDBObject("First_Name",-1));

Example

Following is the code snippet to display sorted documents −

import org.bson.Document;

import com.mongodb.BasicDBObject;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class Tester {
   public static void main(String[] args) {
      // Creating a Mongo client 
      MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
      MongoDatabase database = mongoClient.getDatabase("myDb");

      // Get the collection
      MongoCollection<Document> collection = database.getCollection("sampleCollection");
      System.out.println("***Discending Order***");
      
      // Sort in Descending order
      FindIterable<Document> allDocuments = collection.find().sort(new BasicDBObject("First_Name",-1));

      for (Document document : allDocuments) {
         System.out.println(document);
      }
      System.out.println("***Ascending Order***");
      
      // Sort in Ascending order
      allDocuments = collection.find().sort(new BasicDBObject("First_Name",1));

      for (Document document : allDocuments) {
         System.out.println(document);
      }
   }
}

Now, let's compile and run the above program as shown below.

$javac Tester.java 
$java Tester

Output

On executing, the above program gives you the following output.

Document{{_id=60b70d426214461f10ac5c9a, First_Name=Radhika, Last_Name=Sharma, Date_Of_Birth=1995-09-26, e_mail=radhika_sharma.123@gmail.com, phone=9000012345}}
Document{{_id=60b70d426214461f10ac5c9b, First_Name=Rachel, Last_Name=Christopher, Date_Of_Birth=1990-02-16, e_mail=Rachel_Christopher.123@gmail.com, phone=9000054321}}
Document{{_id=60b70d426214461f10ac5c9c, First_Name=Fathima, Last_Name=Sheik, Date_Of_Birth=1990-02-16, e_mail=Fathima_Sheik.123@gmail.com, phone=9000054321}}
***Ascending Order***
Document{{_id=60b70d426214461f10ac5c9c, First_Name=Fathima, Last_Name=Sheik, Date_Of_Birth=1990-02-16, e_mail=Fathima_Sheik.123@gmail.com, phone=9000054321}}
Document{{_id=60b70d426214461f10ac5c9b, First_Name=Rachel, Last_Name=Christopher, Date_Of_Birth=1990-02-16, e_mail=Rachel_Christopher.123@gmail.com, phone=9000054321}}
Document{{_id=60b70d426214461f10ac5c9a, First_Name=Radhika, Last_Name=Sharma, Date_Of_Birth=1995-09-26, e_mail=radhika_sharma.123@gmail.com, phone=9000012345}}
Advertisements