MongoDB Java CRUD Example Tutorial

Welcome to MongoDB Java Example Tutorial. Earlier we learned how to install MongoDB in Unix machines and executed some commands from terminal. Today we will look into the MongoDB Java Driver features and how to perform common CRUD (Create, Read, Update, Delete) operations.

  • MongoDB Java Driver Download

    If you have maven project, just add below dependency to include MongoDB java driver into your application.

    If you have a standalone project, you can download MongoDB Java Driver from this link and include it in your project build path.

    Now let’s go through some basic usage of MongoDB java driver and then we will look into MongoDB Java Example program for CRUD operations.

  • Creating MongoDB Java Connection

    MongoClient is the interface between our java program and MongoDB server. MongoClient is used to create connection, connect to database, retrieve collection names and create/read/update/delete database, collections, document etc.

    One of the MongoDB java driver feature I like most is that it’s thread safe, so we can create an instance of MongoClient once and reuse it. Even if multiple thread accesses it simultaneously, a connection is returned from the internal connection pool maintained by it.

    For every request to the database (find, insert etc) the Java thread will obtain a connection from the pool, execute the operation, and release the connection. This means the connection (socket) used may be different each time.

    Below are some of the common methods to connect to a MongoDB server.

  • Connection to MongoDB Database

    Once we get the connection to MongoDB server, next step is to create the connection to the database, as shown below. Note that if database is not present, MongoDB will create it for you.

    MongoClient provide a useful method to get all the database names, as shown below.

    We can have user-password based authentication for databases, in that case we need to provide authorization credentials like below.

    If you are using older versions, you need to provide authentication details after getting the database object like below.

    You can easily figure out flaws in the earlier approach, the authentication should be done at early stage because we can’t recover from it.

    We can drop a database either by using MongoClient dropDatabase(String db) method or by DB dropDatabase() method. Since we are dropping the database, i prefer to use MongoClient method.

  • MongoDB and Collections

    Every database can have zero or multiple collections, they are like tables in relational database servers except that you don’t have specific format of data. Think of it like a generic list vs list of Strings in terms of java programming language.

    We can get all the collections names using below code.

    We can get a specific collection by providing it’s name, as shown below.

    Again if the collection doesn’t exist, MongoDB will create it for you. All the data in MongoDB goes into some collection, so at this point we are ready to perform insert/update/delete operations.

    We can use DBCollection drop() method to drop a collection from the database.

  • MongoDB Java Example

    Even though we can work on any valid JSON document in MongoDB collection, in real life we have POJO classes that are mapped with these data. So I will create a java bean and use it for my examples.

    Here is the complete MongoDB java example program showing all the CRUD operations one by one.

    A sample execution results in following output.

    Notice that I am saving User id with _id name, this is a reserved key for the primary key of any record in the collection. If we don’t provide one, MongoDB will create one for us. It’s like sequencer or auto increment column in relational database tables.

    Since I am deleting the created record, further execution won’t cause any issues. But if there are duplicate record, then we will get below errors.

That’s all for getting your started with MongoDB Java Driver, we will look into more features in next posts.

By admin

Leave a Reply

%d bloggers like this: