Inserting Document using MongoDB Java Driver

0

In this article, we will be inserting documents using MongDB java driver. If you haven’t installed MongoDb, read here for an introduction and the installation steps.

We will be using Maven as our build tool. In order to access MongoDB Java Driver API, include mongodb-driver artifact.

Dependencies

Add mongodb-driver artifact to your pom.xml.

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>com.javarticles.spring.jms</groupId>
	<artifactId>springJms</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>
		<dependency>
			<groupId>org.mongodb</groupId>
			<artifactId>mongo-java-driver</artifactId>
			<version>3.2.0</version>
		</dependency>
	</dependencies>

</project>

Connecting to database

The first thing to do is to connect to the database.

We need to create an instance of com.mongodb.MongoClient. A MongoClient instance represents your Java connection to the MongoDB database. For most applications, you should have one MongoClient instance for the entire JVM, it holds a pool of connections to the database.

MongoClient comes with many flavors of constructors. We will use the default constructor if the database resides in the localhost listening on the default port (27017).

MongoClient mongoClient = new MongoClient();

If you want to connect to a mongoDB running on a specific machine and port then you need to pass in the host name and port.

MongoClient mongoClient = new MongoClient("localhost", 27017);

Retrieving database

Once we have the connection instance, we need to retrieve the database instance.

MongoDatabase database = mongoClient.getDatabase("mydb");

Getting Collection

Mongo database consists of collections, a collection is analogous to a relational database’s table and a document is analogous to a table row. Each collection contains a set of MongoDB documents.

We will insert document into a collection so we need to first get the collection. We need to call getCollection(collectionName) on the MongoDatabase instance and pass in the collection name.

MongoCollection product = database
                    .getCollection("product");

Insert Document

To insert document we will call one of the insert method on the MongoCollection object. To create the document using the Java driver we will use the Document class.

Document doc = new Document("product", "Comfi Bunk Bed")
                    .append("finish", "Dark walnut")
                    .append("desc", "Perfect finish").append("price", "33000");

To insert the document, call insertOne() on the collection object. The

product.insertOne(doc);

Here is the full example. The Document object uses fluent style API to create key-value pairs by appending them using append(key, value).

MongoDBInsertExample:

package com.javarticles.mongodb;

import java.net.UnknownHostException;

import org.bson.Document;

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

public class MongoDBInsertExample {
    public static void main(String[] args) throws UnknownHostException {

        MongoClient mongoClient = new MongoClient();
        try {
            MongoDatabase database = mongoClient.getDatabase("mydb");
            MongoCollection<Document> product = database
                    .getCollection("product");
            product.insertOne(new Document("product", "Comfi Bunk Bed")
                    .append("finish", "Dark walnut")
                    .append("desc", "Perfect finish").append("price", "33000"));

            MongoCursor<Document> cursor = product.find().iterator();
            try {
                while (cursor.hasNext()) {
                    Document document = cursor.next();
                    System.out.println(document);
                    product.deleteOne(document);
                }
            } finally {
                cursor.close();
            }
        } finally {
            mongoClient.close();
        }
    }
}

Output:

Document{{_id=568693a1ef900618b0fe43b9, product=Comfi Bunk Bed, finish=Dark walnut, desc=Perfect finish, price=33000}}

Query Inserted Document

We would like to query the inserted document. To find all the documents in the collection, call MongoCollection.find(). It returns an Iterable object which can either iterate through using foreach loop or call iterator() to return an iterator object to go over the database result.

            MongoCursor<Document> cursor = product.find().iterator();
            try {
                while (cursor.hasNext()) {
                    Document document = cursor.next();
                    System.out.println(document);
                    product.deleteOne(document);
                }
            } finally {
                cursor.close();
            }

Insert Multiple Documents

If you want to insert multiple documents, you can add the individual documents to a List and then pass it as an argument to the insertMany() method of your collection.
To iterate through the documents we have used the foreach style lopping on the iterable object.

for (Document document : product.find()) {
    System.out.println(document.toJson());
    product.deleteOne(document);
}

MongoDBInsertManyExample:

package com.javarticles.mongodb;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class MongoDBInsertManyExample {
    public static void main(String[] args) throws UnknownHostException {

        MongoClient mongoClient = new MongoClient();
        try {
            MongoDatabase database = mongoClient.getDatabase("mydb");
            MongoCollection product = database
                    .getCollection("product");
            List documentList = new ArrayList();
            documentList.add(new Document("product", "Study Table"));
            documentList.add(new Document("product", "Wooden Chair"));
            product.insertMany(documentList);
            
            for (Document document : product.find()) {
                System.out.println(document.toJson());
                product.deleteOne(document);
            }            
        } finally {
            mongoClient.close();
        }
    }
}

Output:

{ "_id" : { "$oid" : "56869200ef9006333c548e75" }, "product" : "Study Table" }
{ "_id" : { "$oid" : "56869200ef9006333c548e76" }, "product" : "Wooden Chair" }

Download the source code

This was an example about Inserting Documents using MongoDB Java Driver.

You can download the source code here: mongoDBInsertExample.zip
Share.

Comments are closed.