Mongodb tutorial for java

MongoDB — Java

In this chapter, we will learn how to set up MongoDB CLIENT.

Installation

Before you start using MongoDB in your Java programs, you need to make sure that you have MongoDB CLIENT and Java set up on the machine. You can check Java tutorial for Java installation on your machine. Now, let us check how to set up MongoDB CLIENT.

  • You need to download the jar mongodb-driver-3.11.2.jar and its dependency mongodb-driver-core-3.11.2.jar.. Make sure to download the latest release of these jar files.
  • You need to include the downloaded jar files into your classpath.

Connect to Database

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

Following is the code snippet to connect to the database −

import com.mongodb.client.MongoDatabase; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; public class ConnectToDB < public static void main( String args[] ) < // Creating a Mongo client MongoClient mongo = new MongoClient( "localhost" , 27017 ); // Creating Credentials MongoCredential credential; credential = MongoCredential.createCredential("sampleUser", "myDb", "password".toCharArray()); System.out.println("Connected to the database successfully"); // Accessing the database MongoDatabase database = mongo.getDatabase("myDb"); System.out.println("Credentials ::"+ credential); >>

Now, let’s compile and run the above program to create our database myDb as shown below.

$javac ConnectToDB.java $java ConnectToDB

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

Connected to the database successfully Credentials ::MongoCredential< mechanism = null, userName = 'sampleUser', source = 'myDb', password = , mechanismProperties = <> >

Create a Collection

To create a collection, createCollection() method of com.mongodb.client.MongoDatabase class is used.

Читайте также:  Dynamic typing in python

Following is the code snippet to create a collection −

import com.mongodb.client.MongoDatabase; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; public class CreatingCollection < public static void main( String args[] ) < // Creating a Mongo client MongoClient mongo = new MongoClient( "localhost" , 27017 ); // Creating Credentials MongoCredential credential; credential = MongoCredential.createCredential("sampleUser", "myDb", "password".toCharArray()); System.out.println("Connected to the database successfully"); //Accessing the database MongoDatabase database = mongo.getDatabase("myDb"); //Creating a collection database.createCollection("sampleCollection"); System.out.println("Collection created successfully"); >>

On compiling, the above program gives you the following result −

Connected to the database successfully Collection created successfully

Getting/Selecting a Collection

To get/select a collection from the database, getCollection() method of com.mongodb.client.MongoDatabase class is used.

Following is the program to get/select a collection −

import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; public class selectingCollection < public static void main( String args[] ) < // Creating a Mongo client MongoClient mongo = new MongoClient( "localhost" , 27017 ); // Creating Credentials MongoCredential credential; credential = MongoCredential.createCredential("sampleUser", "myDb", "password".toCharArray()); System.out.println("Connected to the database successfully"); // Accessing the database MongoDatabase database = mongo.getDatabase("myDb"); // Creating a collection System.out.println("Collection created successfully"); // Retrieving a collection MongoCollectioncollection = database.getCollection("myCollection"); System.out.println("Collection myCollection selected successfully"); > >

On compiling, the above program gives you the following result −

Connected to the database successfully Collection created successfully Collection myCollection selected successfully

Insert a Document

To insert a document into MongoDB, insert() method of com.mongodb.client.MongoCollection class is used.

Following is the code snippet to insert a document −

import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; import com.mongodb.MongoClient; public class InsertingDocument < public static void main( String args[] ) < // Creating a Mongo client MongoClient mongo = new MongoClient( "localhost" , 27017 ); // Accessing the database MongoDatabase database = mongo.getDatabase("myDb"); // Creating a collection database.createCollection("sampleCollection"); System.out.println("Collection created successfully"); // Retrieving a collection MongoCollectioncollection = database.getCollection("sampleCollection"); System.out.println("Collection sampleCollection selected successfully"); 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); System.out.println("Document inserted successfully"); >

On compiling, the above program gives you the following result −

Connected to the database successfully Collection sampleCollection selected successfully Document inserted successfully

Retrieve All Documents

To select all documents from the collection, find() method of com.mongodb.client.MongoCollection class is used. This method returns a cursor, so you need to iterate this cursor.

Following is the program to select all documents −

import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; public class RetrievingAllDocuments < public static void main( String args[] ) < // Creating a Mongo client MongoClient mongo = new MongoClient( "localhost" , 27017 ); // Creating Credentials MongoCredential credential; credential = MongoCredential.createCredential("sampleUser", "myDb", "password".toCharArray()); System.out.println("Connected to the database successfully"); // Accessing the database MongoDatabase database = mongo.getDatabase("myDb"); // Retrieving a collection MongoCollectioncollection = database.getCollection("sampleCollection"); System.out.println("Collection sampleCollection selected successfully"); Document document1 = new Document("title", "MongoDB") .append("description", "database") .append("likes", 100) .append("url", "http://www.tutorialspoint.com/mongodb/") .append("by", "tutorials point"); Document document2 = new Document("title", "RethinkDB") .append("description", "database") .append("likes", 200) .append("url", "http://www.tutorialspoint.com/rethinkdb/") .append("by", "tutorials point"); List list = new ArrayList(); list.add(document1); list.add(document2); collection.insertMany(list); // Getting the iterable object FindIterable iterDoc = collection.find(); int i = 1; // Getting the iterator Iterator it = iterDoc.iterator(); while (it.hasNext()) < System.out.println(it.next()); i++; >> >

On compiling, the above program gives you the following result −

Connected to the database successfully Collection sampleCollection selected successfully Document> Document>

Update Document

To update a document from the collection, updateOne() method of com.mongodb.client.MongoCollection class is used.

Following is the program to select the first document −

import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; import com.mongodb.client.model.Updates; import java.util.Iterator; import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; public class UpdatingDocuments < public static void main( String args[] ) < // Creating a Mongo client MongoClient mongo = new MongoClient( "localhost" , 27017 ); // Creating Credentials MongoCredential credential; credential = MongoCredential.createCredential("sampleUser", "myDb", "password".toCharArray()); System.out.println("Connected to the database successfully"); // Accessing the database MongoDatabase database = mongo.getDatabase("myDb"); // Retrieving a collection MongoCollectioncollection = database.getCollection("sampleCollection"); System.out.println("Collection myCollection selected successfully"); collection.updateOne(Filters.eq("title", 1), Updates.set("likes", 150)); System.out.println("Document update successfully. "); // Retrieving the documents after updation // Getting the iterable object FindIterable iterDoc = collection.find(); int i = 1; // Getting the iterator Iterator it = iterDoc.iterator(); while (it.hasNext()) < System.out.println(it.next()); i++; >> >

On compiling, the above program gives you the following result −

Connected to the database successfully Collection myCollection selected successfully Document update successfully. Document> Document>

Delete a Document

To delete a document from the collection, you need to use the deleteOne() method of the com.mongodb.client.MongoCollection class.

Following is the program to delete a document −

import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; import java.util.Iterator; import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; public class DeletingDocuments < public static void main( String args[] ) < // Creating a Mongo client MongoClient mongo = new MongoClient( "localhost" , 27017 ); // Creating Credentials MongoCredential credential; credential = MongoCredential.createCredential("sampleUser", "myDb", "password".toCharArray()); System.out.println("Connected to the database successfully"); // Accessing the database MongoDatabase database = mongo.getDatabase("myDb"); // Retrieving a collection MongoCollectioncollection = database.getCollection("sampleCollection"); System.out.println("Collection sampleCollection selected successfully"); // Deleting the documents collection.deleteOne(Filters.eq("title", "MongoDB")); System.out.println("Document deleted successfully. "); // Retrieving the documents after updation // Getting the iterable object FindIterable iterDoc = collection.find(); int i = 1; // Getting the iterator Iterator it = iterDoc.iterator(); while (it.hasNext()) < System.out.println(it.next()); i++; >> >

On compiling, the above program gives you the following result −

Connected to the database successfully Collection sampleCollection selected successfully Document deleted successfully. Document>

Dropping a Collection

To drop a collection from a database, you need to use the drop() method of the com.mongodb.client.MongoCollection class.

Following is the program to delete a collection −

import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; public class DropingCollection < public static void main( String args[] ) < // Creating a Mongo client MongoClient mongo = new MongoClient( "localhost" , 27017 ); // Creating Credentials MongoCredential credential; credential = MongoCredential.createCredential("sampleUser", "myDb", "password".toCharArray()); System.out.println("Connected to the database successfully"); // Accessing the database MongoDatabase database = mongo.getDatabase("myDb"); // Creating a collection System.out.println("Collections created successfully"); // Retrieving a collection MongoCollectioncollection = database.getCollection("sampleCollection"); // Dropping a Collection collection.drop(); System.out.println("Collection dropped successfully"); > >

On compiling, the above program gives you the following result −

Connected to the database successfully Collection sampleCollection selected successfully Collection dropped successfully

Listing All the Collections

To list all the collections in a database, you need to use the listCollectionNames() method of the com.mongodb.client.MongoDatabase class.

Following is the program to list all the collections of a database −

import com.mongodb.client.MongoDatabase; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; public class ListOfCollection < public static void main( String args[] ) < // Creating a Mongo client MongoClient mongo = new MongoClient( "localhost" , 27017 ); // Creating Credentials MongoCredential credential; credential = MongoCredential.createCredential("sampleUser", "myDb", "password".toCharArray()); System.out.println("Connected to the database successfully"); // Accessing the database MongoDatabase database = mongo.getDatabase("myDb"); System.out.println("Collection created successfully"); for (String name : database.listCollectionNames()) < System.out.println(name); >> >

On compiling, the above program gives you the following result −

Connected to the database successfully Collection created successfully myCollection myCollection1 myCollection5

Remaining MongoDB methods save(), limit(), skip(), sort() etc. work same as explained in the subsequent tutorial.

Источник

Getting Started with MongoDB and Java — CRUD Operations Tutorial

The MongoDB Java Driver logging is now enabled via the popular SLF4J API so I added logback in the pom.xml and a configuration file logback.xml .

Introduction

Java badge

In this very first blog post of the Java Quick Start series, I will show you how to set up your Java project with Maven and execute a MongoDB command in Java. Then we will explore the most common operations — such as create, read, update, and delete — using the MongoDB Java driver . I will also show you some of the more powerful options and features available as part of the MongoDB Java driver for each of these operations, giving you a really great foundation of knowledge to build upon as we go through the series.

Why MongoDB and Java?

Java is the most popular language in the IT industry at the date of this blog post, and developers voted MongoDB as their most wanted database four years in a row . In this series of blog posts, I will be demonstrating how powerful these two great pieces of technology are when combined and how you can access that power.

Prerequisites

To follow along, you can use any environment you like and the integrated development environment of your choice. I’ll use Maven 3.6.2 and the Java OpenJDK 13, but all the code will be compatible with Java versions 8 to 13, so feel free to use the JDK of your choice and update the Java version accordingly in the pom.xml file we are about to set up.

For the MongoDB cluster, we will be using a M0 Free Tier MongoDB Cluster from MongoDB Atlas . If you don’t have one already, check out my Get Started with an M0 Cluster blog post.

Get your free M0 cluster on MongoDB Atlas today. It’s free forever, and you’ll be able to use it to work with the examples in this blog series.

Getting set up

To begin with, we will need to set up a new Maven project. You have two options at this point. You can either clone this series’ git repository or you can create and set up the Maven project.

Using the git repository

If you choose to use git, you will get all the code immediately. I still recommend you read through the manual set-up.

Setting up manually

You can either use your favorite IDE to create a new Maven project for you or you can create the Maven project manually. Either way, you should get the following folder architecture:

To verify that everything works correctly, you should be able to create and run a simple «Hello MongoDB!» program. In src/main/java/com/mongodb/quickstart , create the HelloMongoDB.java file:

Then compile and execute it with your IDE or use the command line in the root directory (where the src folder is):

Note: If you see some warnings about an illegal reflective access from guice.java , it’s safe to ignore them. Guice is used by Maven and needs an update. You can read more about it in this GitHub issue . These warnings will disappear in a future release of Guice and Maven.

Connecting with Java

Now that our Maven project works and we have resolved our dependencies, we can start using MongoDB Atlas with Java.

If you have imported the sample dataset as suggested in the Quick Start Atlas blog post , then with the Java code we are about to create, you will be able to see a list of the databases in the sample dataset.

The first step is to instantiate a MongoClient by passing a MongoDB Atlas connection string into the MongoClients.create() static method. This will establish a connection to MongoDB Atlas using the connection string. Then we can retrieve the list of databases on this cluster and print them out to test the connection with MongoDB.

As you can see, the MongoDB connection string is retrieved from the System Properties , so we need to set this up. Once you have retrieved your MongoDB Atlas connection string , you can add the mongodb.uri system property into your IDE. Here is my configuration with IntelliJ for example.

Or if you prefer to use Maven in command line, here is the equivalent command line you can run in the root directory:

Insert operations

Getting set up

In the Connecting with Java section, we created the classes HelloMongoDB and Connection . Now we will work on the Create class.

If you didn’t set up your free cluster on MongoDB Atlas, now is great time to do so. Get the directions for creating your cluster .

Checking the collection and data model

In the sample dataset, you can find the database sample_training , which contains a collection grades . Each document in this collection represents a student’s grades for a particular class.

And here is the extended JSON representation of the same student. You can retrieve it in MongoDB Compass , our free GUI tool, if you want.

Extended JSON is the human readable version of a BSON document without loss of type information. You can read more about the Java driver and BSON in the MongoDB Java driver documentation .

As you can see, MongoDB stores BSON documents and for each key-value pair, the BSON contains the key and the value along with its type. This is how MongoDB knows that class_id is actually a double and not an integer, which is not explicit in the mongo shell representation of this document.

We have 10,000 students ( student_id from 0 to 9999) already in this collection and each of them took 10 different classes, which adds up to 100,000 documents in this collection. Let’s say a new student ( student_id 10,000) just arrived in this university and received a bunch of (random) grades in his first class. Let’s insert this new student document using Java and the MongoDB Java driver.

In this university, the class_id varies from 0 to 500, so I can use any random value between 0 and 500.

Источник

Оцените статью