Java MongoDB Insert a Document Example
Hello readers, in this tutorial, you will learn how to insert the documents into a Mongo collection using the Java driver.
1. Introduction
If you have installed the MongoDB application (version 3.6.X) on Windows or Ubuntu operating system and you wish to learn this tutorial, then follow the below steps. It is very simple, but before moving further let’s take a look at MongoDB and its features.
1.1 What is MongoDB?
- MongoDB is a high-performance NoSQL database where each database has collections which in turn has documents. Each document has a different number of fields, size, content, and is stored in a JSON-like format (i.e. Binary JSON (BSN)
- The documents in MongoDB doesn’t need to have a schema defined beforehand. Instead, the fields (i.e. records) can be created on the go
- Data model available within the MongoDB allows developers to represent the hierarchical relationships, store arrays, and other more complex structures easily
- This NoSQL solution often comes with embedding, auto-sharding, and onboard replication for better scalability and high availability
1.1.1 Why MongoDB?
- As a NoSQL type database, MongoDB stores the data in the form of a document. Thus, MongoDB offers more flexibility
- This database supports search by field-name, range queries, and the regular expressions. It often provides queries to return the particular fields inside the documents
- MongoDB offers indexes to improve the search performance within the NoSQL database
- To offer horizontal scalability, MongoDB uses sharding by splitting the data across the many MongoDB occurrences
- Replication: MongoDB can give high availability with the replica sets
2. Java MongoDB Insert a Document Example
Here is a systematic guide for implementing this tutorial using the MongoDB Java driver.
2.1 Tools Used
We are using Eclipse Kepler SR2, JDK 8, MongoDB and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.
2.2 Project Structure
Firstly, let us review the final project structure, in case you are confused about where you should create the corresponding files or folder later!
2.3 Project Creation
This section will demonstrate how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project
.
In the New Maven Project window, it will ask you to select a project location. By default, Use default workspace location will be selected. Select the Create a simple project (skip archetype selection) checkbox and just click on next button to proceed.
It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT
.
Click on finish and the creation of a maven project will be completed. If you observe, it has downloaded the maven dependencies and a pom.xml
file will be created. It will have the following code:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>JavaMongoDbInsert</groupId> <artifactId>JavaMongoDbInsert</artifactId> <version>0.0.1-SNAPSHOT</version> </project>
We can start adding the dependencies that developers want like MongoDB Java Driver, Log4j etc. Let us start building the application!
3. Application Building
Let us create an application to understand the basic building blocks of this tutorial.
3.1 Maven Dependencies
MongoDB Java driver is an all-in-one jar, which embeds the core driver and BSON. BSON, short for Binary JSON, is a binary-encoded serialization of the JSON-like documents. In this example, we are using the stable MongoDB Java driver version in order to make the database connectivity. The updated file will have the following code:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>JavaMongoDbInsert</groupId> <artifactId>JavaMongoDbInsert</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver --> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.5.0</version> </dependency> <!-- log4j dependency --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies> <build> <finalName>${project.artifactId}</finalName> </build> </project>
3.2 Java Class Creation
Let us write a sample Java program that connects to a Mongo database running on the localhost at a default port and will insert the documents into the collection. Add the following code to it:
MongoDemo.java
package com.jcg.java.mongodb; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase; public class MongoDemo { private static Logger log = Logger.getLogger(MongoDemo.class); // Adding a single document into the mongo collection. private static void addOneDocument(MongoCollection<Document> col) { // Sample document. Document emp1 = new Document(); emp1.put("name", "yatin batra"); emp1.put("website", "javacodegeeks.com"); Document emp1_addr = new Document(); emp1_addr.put("addr_line1", "Savannah, Illinois"); emp1_addr.put("zip_code", "85794"); emp1.put("address", emp1_addr); col.insertOne(emp1); } // Adding the multiple documents into the mongo collection. private static void addMultipleDocuments(MongoCollection<Document> col) { // Sample document. Document emp2 = new Document(); emp2.put("name", "Charlotte Neil"); emp2.put("website", "webcodegeeks.com"); Document emp2_addr = new Document(); emp2_addr.put("addr_line1", "Fremont, AK"); emp2_addr.put("zip_code", "19408"); emp2.put("address", emp2_addr); // Sample document. Document emp3 = new Document(); emp3.put("title", "Ms."); emp3.put("name", "Samantha Greens"); emp3.put("website", "systemcodegeeks.com"); Document emp3_addr = new Document(); emp3_addr.put("addr_line1", "Cudahy, Ohio"); emp3_addr.put("zip_code", "31522"); emp3.put("address", emp3_addr); // Adding documents to a list. List<Document> docs = new ArrayList<Document>(); docs.add(emp2); docs.add(emp3); col.insertMany(docs); } // Fetching all documents from the mongo collection. private static void getAllDocuments(MongoCollection<Document> col) { log.info("Fetching all documents from the collection"); // Performing a read operation on the collection. FindIterable<Document> fi = col.find(); MongoCursor<Document> cursor = fi.iterator(); try { while(cursor.hasNext()) { log.info(cursor.next().toJson()); } } finally { cursor.close(); } } @SuppressWarnings("resource") public static void main(String[] args) { // Mongodb initialization parameters. int port_no = 27017; String host_name = "localhost", db_name = "sampledb", db_coll_name = "emp"; // Mongodb connection string. String client_url = "mongodb://" + host_name + ":" + port_no + "/" + db_name; MongoClientURI uri = new MongoClientURI(client_url); // Connecting to the mongodb server using the given client uri. MongoClient mongo_client = new MongoClient(uri); // Fetching the database from the mongodb. MongoDatabase db = mongo_client.getDatabase(db_name); // Fetching the collection from the mongodb. MongoCollection<Document> coll = db.getCollection(db_coll_name); // Adding a single document in the mongo collection. addOneDocument(coll); log.info("\n"); // Adding the multiple documents in the mongo collection. addMultipleDocuments(coll); log.info("\n"); // Fetching all the documents from the mongodb. getAllDocuments(coll); } }
4. Run the Application
To run the application, developers will need to right click on the MongoDemo.java
class, Run As -> Java Application
5. Project Demo
If everything is fine, the code shows the following logs as output.
That is all for this post. Happy Learning!
6. Conclusion
In this section, developers learned how to insert the documents into the Mongo database using Java. Developers can download the sample application as an Eclipse project in the Downloads section. Remember to update the database connection settings.
7. Download the Eclipse Project
This was an example of inserting the documents to the Mongo database using Java.
You can download the full source code of this example here: JavaMongoDbInsert