Java & MongoDB – Embedded Documents

Java & MongoDB – Embedded Documents ”; Previous Next 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}}] }} Print Page Previous Next Advertisements ”;

Java & MongoDB – Delete Document

Java & MongoDB – Delete Document ”; Previous Next 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, [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}} Print Page Previous Next Advertisements ”;

Java & MongoDB – Quick Guide

Java & MongoDB – Quick Guide ”; Previous Next 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 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. 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

Java & MongoDB – Sorting Records

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 ”;

Java & MongoDB – Drop Database

Java & MongoDB – Drop Database ”; Previous Next 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 Print Page Previous Next Advertisements ”;

Java & MongoDB – Create Collection

Java & MongoDB – Create Collection ”; Previous Next 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. Print Page Previous Next Advertisements ”;

Java & MongoDB – Overview

Java & MongoDB – Overview ”; Previous Next 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. Print Page Previous Next Advertisements ”;

Java & MongoDB – Home

Java & MongoDB Tutorial PDF Version Quick Guide Resources Job Search Discussion 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. Audience This tutorial is designed for Java programmers who would like to understand the MongoDB driver to connect to MongoDB in detail along with its architecture and actual usage. Prerequisites Before proceeding with this tutorial, you should have a good understanding of Java programming language. As you are going to deal with MongoDB database, you should have prior exposure to NoSQL and Database concepts. Print Page Previous Next Advertisements ”;

Java & MongoDB – Display Collections

Java & MongoDB – Display Collections ”; Previous Next 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 Print Page Previous Next Advertisements ”;

Java & MongoDB – Update Document

Java & MongoDB – Update Document ”; Previous Next 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”, “[email protected]”)); 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, [email protected], phone=9034343345}} Print Page Previous Next Advertisements ”;