Java & MongoDB – Select Document ”; Previous Next 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, [email protected], phone=9034343345}} Document{{_id=60b70d426214461f10ac5c9a, First_Name=Radhika, Last_Name=Sharma, Date_Of_Birth=1995-09-26, [email protected], phone=9000012345}} Document{{_id=60b70d426214461f10ac5c9b, First_Name=Rachel, Last_Name=Christopher, Date_Of_Birth=1990-02-16, [email protected], phone=9000054321}} Document{{_id=60b70d426214461f10ac5c9c, First_Name=Fathima, Last_Name=Sheik, Date_Of_Birth=1990-02-16, [email protected], phone=9000054321}} ******** Document{{_id=60b70d426214461f10ac5c99, First_Name=Mahesh, Last_Name=Parashar, Date_Of_Birth=1990-08-21, [email protected], phone=9034343345}} Print Page Previous Next Advertisements ”;
Category: java Mongodb
Java & MongoDB – Discussion
Discuss Java & MongoDB ”; Previous Next Java based application can connect to MongoDB using Java MongoDB Driver. Java MongoDB Driver works with Java on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. Print Page Previous Next Advertisements ”;
Java & MongoDB – Connecting Database ”; Previous Next 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>} Print Page Previous Next Advertisements ”;
Java & MongoDB – Drop Collection ”; Previous Next 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. Print Page Previous Next Advertisements ”;
Java & MongoDB – Insert Document ”; Previous Next 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”, “[email protected]”) .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”, “[email protected]”) .append(“phone”, “9000012345”)); documents.add(new Document(“First_Name”, “Rachel”) .append(“Last_Name”, “Christopher”) .append(“Date_Of_Birth”, “1990-02-16”) .append(“e_mail”, “[email protected]”) .append(“phone”, “9000054321”)); documents.add(new Document(“First_Name”, “Fathima”) .append(“Last_Name”, “Sheik”) .append(“Date_Of_Birth”, “1990-02-16”) .append(“e_mail”, “[email protected]”) .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. Print Page Previous Next Advertisements ”;
Java & MongoDB – Useful Resources ”; Previous Next The following resources contain additional information on Java and MongoDB. Please use them to get more in-depth knowledge on this topic. Useful Links on Java and MongoDB MongoDB Documentation − MongoDB”s official website for its latest docs and updates. MongoDB Downloads − Official website to download latest release of MongoDB. MongoDB Wiki − Wikipedia Reference for MongoDB. Useful Books on Java and MongoDB To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;
Java & MongoDB – Limiting Documents ”; Previous Next 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, [email protected], phone=9000012345}} Document{{_id=60b70d426214461f10ac5c9b, First_Name=Rachel, Last_Name=Christopher, Date_Of_Birth=1990-02-16, [email protected], phone=9000054321}} Print Page Previous Next Advertisements ”;
Java & MongoDB – Show Databases ”; Previous Next 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 Print Page Previous Next Advertisements ”;
Java & MongoDB – Environment Setup ”; Previous Next 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 Filesjavajdk 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:WINDOWSSYSTEM32”, then change your path to read ”C:WINDOWSSYSTEM32;c:Program Filesjavajdkbin”. Setting Up the Path for Windows 95/98/ME Assuming you have installed Java in c:Program Filesjavajdk directory − Edit the ”C:autoexec.bat” file and add the following line at the end − SET PATH=%PATH%;C:Program Filesjavajdkbin 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. Print Page Previous Next Advertisements ”;
Java & MongoDB – Sorting Documents ”; Previous Next 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, [email protected], phone=9000012345}} Document{{_id=60b70d426214461f10ac5c9b, First_Name=Rachel, Last_Name=Christopher, Date_Of_Birth=1990-02-16, [email protected], phone=9000054321}} Document{{_id=60b70d426214461f10ac5c9c, First_Name=Fathima, Last_Name=Sheik, Date_Of_Birth=1990-02-16, [email protected], phone=9000054321}} ***Ascending Order*** Document{{_id=60b70d426214461f10ac5c9c, First_Name=Fathima, Last_Name=Sheik, Date_Of_Birth=1990-02-16, [email protected], phone=9000054321}} Document{{_id=60b70d426214461f10ac5c9b, First_Name=Rachel, Last_Name=Christopher, Date_Of_Birth=1990-02-16, [email protected], phone=9000054321}} Document{{_id=60b70d426214461f10ac5c9a, First_Name=Radhika, Last_Name=Sharma, Date_Of_Birth=1995-09-26, [email protected], phone=9000012345}} Print Page Previous Next Advertisements ”;