Java MongoDB Create Collection Example

This tutorial shows how to create a collection in MongoDB using Java.

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.
Learn MongoDB with Java at https://www.javaguides.net/p/java-mongodb-tutorial.html

Tools and Technologies Used

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

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.

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.

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.

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

Java MongoDB Tutorials

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

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