MongoDB Java Integration Guide: Inserting Documents into MongoDB Collections in Java

This blog teaches you how to insert one or more documents into a MongoDB collection using Java. You will learn how to use the Document, insertOne, insertMany, and Bson classes to perform different insertion operations on MongoDB collections.

1. Introduction

In this tutorial, you will learn how to insert one or more documents into a MongoDB collection using Java. MongoDB is a popular NoSQL database that stores data in JSON-like documents. A document is a basic unit of data in MongoDB, and it consists of one or more key-value pairs. A collection is a group of documents that share a common schema or structure.

To insert documents into a MongoDB collection, you will need to use the MongoDB Java driver, which is a library that provides a Java API for interacting with MongoDB. The MongoDB Java driver allows you to create, read, update, and delete documents from MongoDB collections using Java code. You will also need to use the Document class, which represents a MongoDB document as a Java object. The Document class implements the Bson interface, which is a generic representation of a JSON-like document.

By the end of this tutorial, you will be able to:

  • Set up the MongoDB Java driver and connect to a MongoDB database.
  • Create a MongoDB collection using Java code.
  • Insert a single document into a MongoDB collection using the insertOne method.
  • Insert multiple documents into a MongoDB collection using the insertMany method.
  • Insert documents with different data types, embedded documents, and arrays into a MongoDB collection using Java code.
  • Insert documents with filters and options into a MongoDB collection using the Bson class and its subclasses.

Before you start, you will need to have the following prerequisites:

  • A basic understanding of Java and MongoDB.
  • A MongoDB database running on your local machine or a cloud service.
  • A Java IDE or editor of your choice.
  • The MongoDB Java driver installed on your machine.

Ready to get started? Let’s begin by setting up the MongoDB Java driver and connecting to a MongoDB database.

2. Setting Up the MongoDB Java Driver

The first step to insert documents into a MongoDB collection using Java is to set up the MongoDB Java driver. The MongoDB Java driver is a library that provides a Java API for interacting with MongoDB. You can use the MongoDB Java driver to create, read, update, and delete documents from MongoDB collections using Java code.

To set up the MongoDB Java driver, you will need to do the following:

  1. Add the MongoDB Java driver dependency to your project. You can use Maven, Gradle, or another dependency management tool to add the MongoDB Java driver to your project. The latest version of the MongoDB Java driver is 4.4.0, and you can find the instructions on how to add it to your project here.
  2. Import the MongoDB Java driver classes to your Java code. You will need to import the following classes to use the MongoDB Java driver: MongoClient, MongoClients, MongoDatabase, MongoCollection, Document, and Bson. These classes are located in the com.mongodb.client and org.bson packages.
  3. Create a MongoClient instance to connect to a MongoDB database. You can use the MongoClients.create() method to create a MongoClient instance that connects to a MongoDB database running on your local machine or a cloud service. You can pass a connection string as a parameter to the MongoClients.create() method to specify the host, port, username, password, and other options for the connection. For example, the following code creates a MongoClient instance that connects to a MongoDB database running on localhost on port 27017:
// Create a MongoClient instance
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");

Once you have set up the MongoDB Java driver, you are ready to create a MongoDB collection using Java code.

3. Creating a MongoDB Collection

After you have set up the MongoDB Java driver and connected to a MongoDB database, you can create a MongoDB collection using Java code. A MongoDB collection is a group of documents that share a common schema or structure. You can create a MongoDB collection explicitly or implicitly using the MongoDB Java driver.

To create a MongoDB collection explicitly, you can use the createCollection() method of the MongoDatabase class. The createCollection() method takes the name of the collection as a parameter and creates an empty collection with that name. For example, the following code creates a collection named “products” in the database named “test”:

// Get the database named "test"
MongoDatabase database = mongoClient.getDatabase("test");

// Create a collection named "products"
database.createCollection("products");

To create a MongoDB collection implicitly, you can use the getCollection() method of the MongoDatabase class. The getCollection() method takes the name of the collection as a parameter and returns a MongoCollection instance that represents the collection. If the collection does not exist, the getCollection() method creates it automatically when you insert the first document into it. For example, the following code creates a collection named “customers” in the database named “test” implicitly:

// Get the database named "test"
MongoDatabase database = mongoClient.getDatabase("test");

// Get or create a collection named "customers"
MongoCollection collection = database.getCollection("customers");

Once you have created a MongoDB collection using Java code, you can insert documents into it using the insertOne() and insertMany() methods of the MongoCollection class. You will learn how to use these methods in the next sections.

4. Inserting a Single Document into a MongoDB Collection

Now that you have created a MongoDB collection using Java code, you can insert a single document into it using the insertOne() method of the MongoCollection class. The insertOne() method takes a Document object as a parameter and inserts it into the collection. The Document object represents a MongoDB document as a Java object, and it implements the Bson interface, which is a generic representation of a JSON-like document.

To insert a single document into a MongoDB collection using Java code, you will need to do the following:

    1. Create a Document object and populate it with key-value pairs. You can use the append() method of the Document class to add key-value pairs to the document. The key is a String that represents the name of the field, and the value can be any Java object that can be converted to a Bson type. For example, the following code creates a Document object that represents a product with four fields: name, price, category, and rating:
// Create a Document object
Document product = new Document();

// Populate the document with key-value pairs
product.append("name", "Laptop")
       .append("price", 999.99)
       .append("category", "Electronics")
       .append("rating", 4.5);
    1. Get a MongoCollection instance that represents the collection you want to insert the document into. You can use the getCollection() method of the MongoDatabase class to get a MongoCollection instance that represents the collection. You need to pass the name of the collection and the Document class as parameters to the getCollection() method. For example, the following code gets a MongoCollection instance that represents the “products” collection:
// Get the database named "test"
MongoDatabase database = mongoClient.getDatabase("test");

// Get the collection named "products"
MongoCollection collection = database.getCollection("products", Document.class);
    1. Use the insertOne() method of the MongoCollection class to insert the document into the collection. You need to pass the Document object as a parameter to the insertOne() method. The insertOne() method returns an InsertOneResult object that contains information about the insertion operation, such as the _id of the inserted document. For example, the following code inserts the product document into the “products” collection and prints the _id of the inserted document:
// Insert the document into the collection
InsertOneResult result = collection.insertOne(product);

// Print the _id of the inserted document
System.out.println("Inserted document _id: " + result.getInsertedId());

By using the insertOne() method, you can insert a single document into a MongoDB collection using Java code. You can also insert multiple documents into a MongoDB collection using the insertMany() method, which you will learn in the next section.

5. Inserting Multiple Documents into a MongoDB Collection

In the previous section, you learned how to insert a single document into a MongoDB collection using the insertOne() method of the MongoCollection class. In this section, you will learn how to insert multiple documents into a MongoDB collection using the insertMany() method of the MongoCollection class. The insertMany() method takes a List of Document objects as a parameter and inserts them into the collection. The List of Document objects represents a batch of MongoDB documents as Java objects, and each Document object implements the Bson interface, which is a generic representation of a JSON-like document.

To insert multiple documents into a MongoDB collection using Java code, you will need to do the following:

    1. Create a List of Document objects and populate each Document object with key-value pairs. You can use the append() method of the Document class to add key-value pairs to each document. The key is a String that represents the name of the field, and the value can be any Java object that can be converted to a Bson type. For example, the following code creates a List of three Document objects that represent three products with four fields each: name, price, category, and rating:
// Create a List of Document objects
List products = new ArrayList<>();

// Populate the first document with key-value pairs
Document product1 = new Document();
product1.append("name", "Mouse")
        .append("price", 19.99)
        .append("category", "Electronics")
        .append("rating", 4.0);

// Populate the second document with key-value pairs
Document product2 = new Document();
product2.append("name", "Keyboard")
        .append("price", 29.99)
        .append("category", "Electronics")
        .append("rating", 4.2);

// Populate the third document with key-value pairs
Document product3 = new Document();
product3.append("name", "Monitor")
        .append("price", 199.99)
        .append("category", "Electronics")
        .append("rating", 4.4);

// Add the documents to the list
products.add(product1);
products.add(product2);
products.add(product3);
    1. Get a MongoCollection instance that represents the collection you want to insert the documents into. You can use the getCollection() method of the MongoDatabase class to get a MongoCollection instance that represents the collection. You need to pass the name of the collection and the Document class as parameters to the getCollection() method. For example, the following code gets a MongoCollection instance that represents the “products” collection:
// Get the database named "test"
MongoDatabase database = mongoClient.getDatabase("test");

// Get the collection named "products"
MongoCollection collection = database.getCollection("products", Document.class);
    1. Use the insertMany() method of the MongoCollection class to insert the documents into the collection. You need to pass the List of Document objects as a parameter to the insertMany() method. The insertMany() method returns an InsertManyResult object that contains information about the insertion operation, such as the _ids of the inserted documents. For example, the following code inserts the products documents into the “products” collection and prints the _ids of the inserted documents:
// Insert the documents into the collection
InsertManyResult result = collection.insertMany(products);

// Print the _ids of the inserted documents
System.out.println("Inserted documents _ids: " + result.getInsertedIds());

By using the insertMany() method, you can insert multiple documents into a MongoDB collection using Java code. You can also insert documents with different data types, embedded documents, and arrays into a MongoDB collection using Java code, which you will learn in the next section.

6. Inserting Documents with Different Data Types into a MongoDB Collection

In the previous sections, you learned how to insert documents into a MongoDB collection using the insertOne() and insertMany() methods of the MongoCollection class. These methods allow you to insert documents that have simple data types, such as strings, numbers, booleans, and nulls. However, MongoDB supports many other data types, such as dates, binary data, object ids, and decimals. How can you insert documents that have these data types into a MongoDB collection using Java code?

The answer is to use the Bson class and its subclasses. The Bson class is a generic representation of a JSON-like document, and it implements the Bson interface, which is also implemented by the Document class. The Bson class has many subclasses that represent different Bson types, such as BsonDateTime, BsonBinary, BsonObjectId, and BsonDecimal128. You can use these subclasses to create Bson values that correspond to the MongoDB data types, and then use them as values in your documents.

To insert documents with different data types into a MongoDB collection using Java code, you will need to do the following:

    1. Import the Bson class and its subclasses from the org.bson package. You will need to import the following classes to use the Bson types: Bson, BsonDateTime, BsonBinary, BsonObjectId, and BsonDecimal128.
    2. Create a Document object and populate it with key-value pairs. You can use the append() method of the Document class to add key-value pairs to the document. The key is a String that represents the name of the field, and the value can be a Bson value that corresponds to the MongoDB data type. For example, the following code creates a Document object that represents a product with six fields: name, price, category, rating, date, and image. The date field has a BsonDateTime value that represents the current date and time, and the image field has a BsonBinary value that represents a binary data of an image:
// Create a Document object
Document product = new Document();

// Populate the document with key-value pairs
product.append("name", "Camera")
       .append("price", 299.99)
       .append("category", "Electronics")
       .append("rating", 4.3)
       .append("date", new BsonDateTime(System.currentTimeMillis()))
       .append("image", new BsonBinary(getImageBytes("camera.jpg")));
    1. Get a MongoCollection instance that represents the collection you want to insert the document into. You can use the getCollection() method of the MongoDatabase class to get a MongoCollection instance that represents the collection. You need to pass the name of the collection and the Document class as parameters to the getCollection() method. For example, the following code gets a MongoCollection instance that represents the “products” collection:
// Get the database named "test"
MongoDatabase database = mongoClient.getDatabase("test");

// Get the collection named "products"
MongoCollection collection = database.getCollection("products", Document.class);
    1. Use the insertOne() method of the MongoCollection class to insert the document into the collection. You need to pass the Document object as a parameter to the insertOne() method. The insertOne() method returns an InsertOneResult object that contains information about the insertion operation, such as the _id of the inserted document. For example, the following code inserts the product document into the “products” collection and prints the _id of the inserted document:
// Insert the document into the collection
InsertOneResult result = collection.insertOne(product);

// Print the _id of the inserted document
System.out.println("Inserted document _id: " + result.getInsertedId());

By using the Bson class and its subclasses, you can insert documents with different data types into a MongoDB collection using Java code. You can also insert documents with embedded documents and arrays into a MongoDB collection using Java code, which you will learn in the next section.

7. Inserting Documents with Embedded Documents and Arrays into a MongoDB Collection

Another feature of MongoDB is that it allows you to insert documents that have embedded documents and arrays as values. An embedded document is a document that is nested inside another document as a value. An array is a list of values that can be of any Bson type, including embedded documents. You can use embedded documents and arrays to model complex and hierarchical data structures in MongoDB.

To insert documents with embedded documents and arrays into a MongoDB collection using Java code, you will need to do the following:

    1. Create a Document object and populate it with key-value pairs. You can use the append() method of the Document class to add key-value pairs to the document. The key is a String that represents the name of the field, and the value can be a Document object or a List of values that represent an embedded document or an array, respectively. For example, the following code creates a Document object that represents a product with seven fields: name, price, category, rating, date, image, and reviews. The reviews field has an array of embedded documents, each representing a review with three fields: user, comment, and rating:
// Create a Document object
Document product = new Document();

// Populate the document with key-value pairs
product.append("name", "Headphones")
       .append("price", 49.99)
       .append("category", "Electronics")
       .append("rating", 4.1)
       .append("date", new BsonDateTime(System.currentTimeMillis()))
       .append("image", new BsonBinary(getImageBytes("headphones.jpg")))
       .append("reviews", Arrays.asList(
           new Document("user", "Alice")
                  .append("comment", "Great sound quality")
                  .append("rating", 5),
           new Document("user", "Bob")
                  .append("comment", "A bit tight on the ears")
                  .append("rating", 3),
           new Document("user", "Charlie")
                  .append("comment", "Good value for money")
                  .append("rating", 4)
       ));
    1. Get a MongoCollection instance that represents the collection you want to insert the document into. You can use the getCollection() method of the MongoDatabase class to get a MongoCollection instance that represents the collection. You need to pass the name of the collection and the Document class as parameters to the getCollection() method. For example, the following code gets a MongoCollection instance that represents the “products” collection:
// Get the database named "test"
MongoDatabase database = mongoClient.getDatabase("test");

// Get the collection named "products"
MongoCollection collection = database.getCollection("products", Document.class);
    1. Use the insertOne() method of the MongoCollection class to insert the document into the collection. You need to pass the Document object as a parameter to the insertOne() method. The insertOne() method returns an InsertOneResult object that contains information about the insertion operation, such as the _id of the inserted document. For example, the following code inserts the product document into the “products” collection and prints the _id of the inserted document:
// Insert the document into the collection
InsertOneResult result = collection.insertOne(product);

// Print the _id of the inserted document
System.out.println("Inserted document _id: " + result.getInsertedId());

By using embedded documents and arrays, you can insert documents with complex and hierarchical data structures into a MongoDB collection using Java code. You can also insert documents with filters and options into a MongoDB collection using Java code, which you will learn in the next section.

8. Inserting Documents with Filters and Options into a MongoDB Collection

So far, you have learned how to insert documents into a MongoDB collection using the insertOne() and insertMany() methods of the MongoCollection class. These methods insert the documents as they are, without applying any filters or options to them. However, sometimes you may want to insert documents with some filters or options, such as specifying the write concern, the order of insertion, or the bypass document validation flag. How can you insert documents with filters and options into a MongoDB collection using Java code?

The answer is to use the InsertOneOptions and InsertManyOptions classes. These classes are helper classes that allow you to specify various filters and options for the insertion operations. You can create an instance of these classes and pass them as a parameter to the insertOne() and insertMany() methods, respectively. The InsertOneOptions and InsertManyOptions classes have several methods that allow you to set different filters and options, such as writeConcern(), ordered(), and bypassDocumentValidation(). You can use these methods to configure the insertion operations according to your needs.

To insert documents with filters and options into a MongoDB collection using Java code, you will need to do the following:

    1. Create a Document object or a List of Document objects and populate them with key-value pairs. You can use the append() method of the Document class to add key-value pairs to the document or documents. The key is a String that represents the name of the field, and the value can be any Java object that can be converted to a Bson type. For example, the following code creates a Document object that represents a product with four fields: name, price, category, and rating:
// Create a Document object
Document product = new Document();

// Populate the document with key-value pairs
product.append("name", "Speaker")
       .append("price", 59.99)
       .append("category", "Electronics")
       .append("rating", 4.3);
    1. Create an instance of the InsertOneOptions or InsertManyOptions class and set the filters and options for the insertion operation. You can use the methods of these classes to set the write concern, the order of insertion, and the bypass document validation flag. For example, the following code creates an instance of the InsertOneOptions class and sets the write concern to MAJORITY, the order of insertion to false, and the bypass document validation flag to true:
// Create an instance of the InsertOneOptions class
InsertOneOptions options = new InsertOneOptions();

// Set the write concern to MAJORITY
options.writeConcern(WriteConcern.MAJORITY);

// Set the order of insertion to false
options.ordered(false);

// Set the bypass document validation flag to true
options.bypassDocumentValidation(true);
    1. Get a MongoCollection instance that represents the collection you want to insert the document or documents into. You can use the getCollection() method of the MongoDatabase class to get a MongoCollection instance that represents the collection. You need to pass the name of the collection and the Document class as parameters to the getCollection() method. For example, the following code gets a MongoCollection instance that represents the “products” collection:
// Get the database named "test"
MongoDatabase database = mongoClient.getDatabase("test");

// Get the collection named "products"
MongoCollection collection = database.getCollection("products", Document.class);
    1. Use the insertOne() or insertMany() method of the MongoCollection class to insert the document or documents into the collection. You need to pass the Document object or the List of Document objects as the first parameter, and the InsertOneOptions or InsertManyOptions instance as the second parameter. The insertOne() or insertMany() method returns an InsertOneResult or InsertManyResult object that contains information about the insertion operation, such as the _ids of the inserted documents. For example, the following code inserts the product document into the “products” collection with the specified options and prints the _id of the inserted document:
// Insert the document into the collection with the specified options
InsertOneResult result = collection.insertOne(product, options);

// Print the _id of the inserted document
System.out.println("Inserted document _id: " + result.getInsertedId());

By using the InsertOneOptions and InsertManyOptions classes, you can insert documents with filters and options into a MongoDB collection using Java code. You have now learned how to insert documents into a MongoDB collection using Java code in various ways. In the next and final section, you will learn how to conclude your tutorial and provide some additional resources for the readers.

9. Conclusion

Congratulations! You have completed this tutorial on how to insert documents into a MongoDB collection using Java code. You have learned how to:

  • Set up the MongoDB Java driver and connect to a MongoDB database.
  • Create a MongoDB collection using Java code.
  • Insert a single document into a MongoDB collection using the insertOne() method.
  • Insert multiple documents into a MongoDB collection using the insertMany() method.
  • Insert documents with different data types into a MongoDB collection using the Bson class and its subclasses.
  • Insert documents with embedded documents and arrays into a MongoDB collection using Java code.
  • Insert documents with filters and options into a MongoDB collection using the InsertOneOptions and InsertManyOptions classes.

By following this tutorial, you have gained a practical understanding of how to use the MongoDB Java driver to perform insertion operations on MongoDB collections. You have also learned how to use the Document and Bson classes to represent MongoDB documents as Java objects, and how to use the MongoCollection class to interact with MongoDB collections using Java code.

We hope you enjoyed this tutorial and found it useful. If you want to learn more about the MongoDB Java driver, you can check out the following resources:

Thank you for reading this tutorial. We hope you have learned something new and useful. Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *