Java MongoDB Create or Insert Document Example Tutorial

This tutorial shows how to use create or insert operations to add new documents to a collection in MongoDB using a Java program.
We will learn how to insert single or multiple documents in the collection. If the collection does not currently exist, insert operations will create the collection.
MongoDB provides the following methods to insert documents into a collection:
  • db.collection.insertOne()
  • db.collection.insertMany()
In this tutorial, we are going to use the above methods to insert single or multiple documents in the collection.
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

Let's 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 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.
A 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);

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);
        }
    }
}

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