MongoDB Java CRUD Operations Example Tutorial

In this tutorial, we will learn how to perform common CRUD (Create, Read, Update, Delete) operations in MongoDB using Java 10.

Table of Contents

  1. MongoDB Overview
  2. Tools and Technologies Used
  3. Installing MongoDB
  4. Create Database
  5. Java MongoDB Driver
  6. Java MongoDB Connection Example
  7. Java MongoDB Create Collection Example
  8. Java MongoDB Insert Single Document Example - insertOne() Method
  9. Java MongoDB Insert Multiple Documents Example - insertMany() Method
  10. Java MongoDB Update Document Example - updateOne() Method
  11. Java MongoDB Read Document Example - find() Method
  12. Java MongoDB Read Document Example - find() Method
All MongoDBJava tutorials at https://www.javaguides.net/p/java-mongodb-tutorial.html

Video Tutorial

This tutorial explained in below YouTube video:

1. MongoDB Overview

MongoDB is a cross-platform, document-oriented database that provides, high performance, high availability, and easy scalability. MongoDB works on the concept of collection and document.

Before getting started with MongoDB CRUD example, let's first familiar with few MongoDB basic concepts like database, collection, and document.

Database

The database is a physical container for collections. Each database gets its own set of files on the file system. A single MongoDB server typically has multiple databases.

Collection

A collection is a group of MongoDB documents. It is the equivalent of an RDBMS table. A collection exists within a single database. Collections do not enforce a schema. Documents within a collection can have different fields. Typically, all documents in a collection are of similar or related purposes.

Document

A document is a set of key-value pairs. Documents have a dynamic schema. Dynamic schema means that documents in the same collection do not need to have the same set of fields or structures, and common fields in a collection's documents may hold different types of data.

2. Tools and Technologies Used

  • Java (JDK) 10
  • Maven 3.5+
  • Eclipse Neon
  • MongoDB 3.12.0

3. Installing MongoDB

Use the following article to install MongoDB on Windows 10.
Make sure that you have installed MongoDB and started MongoDB server on default port 27017.

4. Create Database

Create a new database by using the below command on the MongoDB client terminal:
> use javaguides;
switched to db javaguides
The use command will create a new database if it doesn't exist, otherwise, it will return the existing database.

5. Java MongoDB Driver

We use the following Maven declaration to include the MongoDB Java Driver in our maven project.
<!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver -->
<dependency>
 <groupId>org.mongodb</groupId>
 <artifactId>mongo-java-driver</artifactId>
 <version>3.12.0</version>
</dependency>
Note that it is an all-in-one JAR, which embeds the core driver and BSON. BSON, short for Bin­ary JSON, is a bin­ary-en­coded seri­al­iz­a­tion of JSON-like doc­u­ments.

6. Java MongoDB Connection Example

This example connects to the "javaguides" database and retrieves all its collections. A MongoClient class is used to connect to the MongoDB server. It is created with the MongoClients.create() method call. The 27017 is the default port on which the MongoDB server listens.
Here is the complete example to MongoDB server using Java:
package net.javaguides.mongodb.database;

import com.mongodb.client.MongoClients;

/**
 * Java MongoDB Connection Example
 * @author Ramesh Fadatare
 *
 */
public class ConnectToDB {
    public static void main(String args[]) {

        try (var mongoClient = MongoClients.create("mongodb://localhost:27017")) {

            var database = mongoClient.getDatabase("javaguides");

            System.out.println("database name -> " + database.getName());

            for (String name: database.listCollectionNames()) {

                System.out.println(name);
            }
        }
    }
}
Output:
database name -> javaguides
users

7. Java MongoDB Create Collection Example

The MongoDatabase's createCollection() method creates a new collection in the database. The MongoCollection's insertMany() method inserts one or more documents into the collection.
This example creates a "users" collection and inserts five documents into it.
package net.javaguides.mongodb.collection;

import java.util.ArrayList;

import org.bson.Document;

import com.mongodb.MongoCommandException;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;

/**
 * Java MongoDB Create Collection Example
 * @author Ramesh Fadatare
 *
 */
public class MongoCreateCollection {

    public static void main(String[] args) {

        try (var mongoClient = MongoClients.create("mongodb://localhost:27017")) {

            var database = mongoClient.getDatabase("javaguides");

            try {
                database.createCollection("users");
                System.out.println("Collection created successfully");
            } catch (MongoCommandException e) {
                database.getCollection("users").drop();
            }

            var docs = new ArrayList < Document > ();

            MongoCollection < Document > collection = database.getCollection("users");

            var d1 = new Document("_id", 1);
            d1.append("_firstName", "Ramesh");
            d1.append("_lastName", "Fadatare");
            docs.add(d1);

            var d2 = new Document("_id", 2);
            d2.append("_firstName", "Tony");
            d2.append("_lastName", "Stark");
            docs.add(d2);

            var d3 = new Document("_id", 3);
            d3.append("_firstName", "Tom");
            d3.append("_lastName", "Cruise");
            docs.add(d3);

            var d4 = new Document("_id", 4);
            d4.append("_firstName", "Amir");
            d4.append("_lastName", "Khan");
            docs.add(d4);

            var d5 = new Document("_id", 5);
            d5.append("_firstName", "Umesh");
            d5.append("_lastName", "Fadatare");
            docs.add(d5);

            collection.insertMany(docs);
        }
    }
}
Output:
Collection created successfully

8. Java MongoDB Insert Single Document Example - insertOne() Method

Let's use insertOne() method to insert a single document into a collection:
package net.javaguides.mongodb.document;

import org.bson.Document;

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

/**
 * MongoDB Insert Single Document Example
 * @author Ramesh Fadatare
 *
 */
public class MongoInsertSingleDocument {

    public static void main(String[] args) {
        try (var mongoClient = MongoClients.create("mongodb://localhost:27017")) {

            var database = mongoClient.getDatabase("javaguides");

            MongoCollection < Document > collection = database.getCollection("users");

            var d1 = new Document("_id", 6);
            d1.append("_firstName", "ABC");
            d1.append("_lastName", "XYZ");

            collection.insertOne(d1);
        }
    }
}
Let's understand the above example.
MongoCollection of documents is created with the getCollection() method:
 MongoCollection < Document > collection = database.getCollection("users");
A new Document is created. It contains the information about the user — id, first name and last name:
            var d1 = new Document("_id", 6);
            d1.append("_firstName", "ABC");
            d1.append("_lastName", "XYZ");
The document inserted to the collection with the insertOne() method:
 collection.insertOne(d1);

9. Java MongoDB Insert Multiple Documents Example - insertMany() Method

The MongoCollection's insertMany() method inserts one or more documents into the collection.
package net.javaguides.mongodb.document;

import java.util.ArrayList;

import org.bson.Document;

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

/**
 * MongoDB Insert Multiple Documents Example
 * @author Ramesh Fadatare
 *
 */
public class MongoInsertDocumentsInCollection {

    public static void main(String[] args) {

        try (var mongoClient = MongoClients.create("mongodb://localhost:27017")) {

            var database = mongoClient.getDatabase("javaguides");

            var docs = new ArrayList < Document > ();

            MongoCollection < Document > collection = database.getCollection("users");

            var d1 = new Document("_id", 1);
            d1.append("_firstName", "Ramesh");
            d1.append("_lastName", "Fadatare");
            docs.add(d1);

            var d2 = new Document("_id", 2);
            d2.append("_firstName", "Tony");
            d2.append("_lastName", "Stark");
            docs.add(d2);

            var d3 = new Document("_id", 3);
            d3.append("_firstName", "Tom");
            d3.append("_lastName", "Cruise");
            docs.add(d3);

            var d4 = new Document("_id", 4);
            d4.append("_firstName", "Amir");
            d4.append("_lastName", "Khan");
            docs.add(d4);

            var d5 = new Document("_id", 5);
            d5.append("_firstName", "Umesh");
            d5.append("_lastName", "Fadatare");
            docs.add(d5);

            collection.insertMany(docs);
        }
    }
}

10. Java MongoDB Update Document Example - updateOne() Method

In the following example, we are updating lastName of the user "Ramesh":
package net.javaguides.mongodb.document;

import java.util.ArrayList;

import org.bson.Document;

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

public class MongoUpdateDocument {
    public static void main(String[] args) {

        // Creating a Mongo client
        try (var mongoClient = MongoClients.create("mongodb://localhost:27017")) {

            // Accessing the database
            MongoDatabase database = mongoClient.getDatabase("javaguides");

            // Retieving a collection
            MongoCollection < Document > collection = database.getCollection("users");

            collection.updateOne(new Document("_firstName", "Ramesh"),
                new Document("$set", new Document("_lastName", "Pawar")));

            // Retrieving the documents after updation
            try (MongoCursor < Document > cur = collection.find().iterator()) {

                while (cur.hasNext()) {

                    var doc = cur.next();
                    var users = new ArrayList < > (doc.values());

                    System.out.printf("%s: %s%n", users.get(1), users.get(2));
                }
            }
        }
    }
}
Output:
Tony: Stark
Tom: Cruise
Amir: Khan
Umesh: Fadatare
Ramesh: Pawar
Note that the lastName of "Ramesh" is changed to "Pawar" with the updateOne() method.
collection.updateOne(new Document("_firstName", "Ramesh"),
                new Document("$set", new Document("_lastName", "Pawar")));

11. Java MongoDB Read Document Example - find() Method

In this example, we iterate over all data of the "users" collection and print to the console.
package net.javaguides.mongodb.document;

import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import org.bson.Document;

import java.util.ArrayList;

/**
 * MongoDB Read Documents Example
 * @author Ramesh Fadatare
 *
 */

public class MongoReadAll {

    public static void main(String[] args) {

        try (var mongoClient = MongoClients.create("mongodb://localhost:27017")) {

            var database = mongoClient.getDatabase("javaguides");

            MongoCollection < Document > collection = database.getCollection("users");

            try (MongoCursor < Document > cur = collection.find().iterator()) {

                while (cur.hasNext()) {

                    var doc = cur.next();
                    var users = new ArrayList < > (doc.values());

                    System.out.printf("%s: %s%n", users.get(1), users.get(2));
                }
            }
        }
    }
}
Output:
Tony: Stark
Tom: Cruise
Amir: Khan
Umesh: Fadatare
Ramesh: Pawar
We retrieve the "users" collection with the getCollection() method:
MongoCollection<Document> collection = database.getCollection("users");
We iterate through the documents of the collection. The find() method finds all documents in the collection:
try (MongoCursor<Document> cur = collection.find().iterator()) {

    while (cur.hasNext()) {

        var doc = cur.next();
        var cars = new ArrayList<>(doc.values());

        System.out.printf("%s: %s%n", cars.get(1), cars.get(2));
    }
}

12. Java MongoDB Delete Document Example - deleteOne() Method

In the following example, we delete a document "_id" = 1:
package net.javaguides.mongodb.document;

import java.util.ArrayList;

import org.bson.Document;

import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

/**
 * MongoDB Delete Documents Example
 * @author Ramesh Fadatare
 *
 */

public class MongoDeleteDocument {

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

            // Accessing the database
            MongoDatabase database = mongoClient.getDatabase("javaguides");

            // Retieving a collection
            MongoCollection < Document > collection = database.getCollection("users");

            // Deleting the documents
            collection.deleteOne(Filters.eq("_id", 1));
            System.out.println("Document deleted successfully...");

            try (MongoCursor < Document > cur = collection.find().iterator()) {

                while (cur.hasNext()) {

                    var doc = cur.next();
                    var users = new ArrayList < > (doc.values());

                    System.out.printf("%s: %s%n", users.get(1), users.get(2));
                }
            }

        }
    }
}
Output:
Document deleted successfully...
Tony: Stark
Tom: Cruise
Amir: Khan
Umesh: Fadatare
The deleteOne() deletes the document of "Ramesh". The eq() creates a filter that matches all documents where the value of the field name equals the specified value.
collection.deleteOne(Filters.eq("_id", 1))

Java MongoDB Tutorials

All Java MongoDB tutorials at https://www.javaguides.net/p/java-mongodb-tutorial.html

References



Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments