Java MongoDB Driver 3.3.0 - Insert Document

 Posted On  | Yashwant Chavan 

In this article we will learn how to insert document using MongoDB 3.3.0 Java Driver. Here I will show you how to use collection.insertOne() and collection.insertMany() API.

Tools and Technologies

Basically we are using below maven dependencies

  1. Maven 3.0.4
  2. JDK 1.8
  3. Mongo Java Driver 3.3.0

Maven Dependencies

To use the mongodb java driver, Define respected maven dependencies of mongo-java-driver in 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.technicalkeeda</groupId>
    <artifactId>JavaExamples</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.3.0</version>
        </dependency>
    </dependencies>
</project>

Connecting to database

A MongoDB client internally uses the connection pooling mechanism. It has one MongoClient instance for the entire JVM. To connect the local mongoDb database use host name "localhost" and default port number "27017".

 MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));

Get the database instance

Once you are successfully connected, access the technicalkeeda database.

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

Get the Collection

Get the collection and insert a document into a collection named books. It will create the collection if the collection does not exist.

 MongoCollection<Document> books = database.getCollection("books");

Insert a Document

Refer below example, Here we are using two methods insertOne() and insertMany(). You can use .append(key, value) method to append the document data in the form key-value pair.

insertOne() - is used to insert single document into books collection.

insertMany() - is used to insert multiple documents into books collection. Pass the documents List to insertMany() method.

package com.technicalkeeda.app;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.bson.Document;

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

public class App {
    public static void main(String[] args) {
        MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
        try {
            MongoDatabase database = mongoClient.getDatabase("technicalkeeda");
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);

            // using insertOne
            MongoCollection < Document > books = database.getCollection("books");
            books.insertOne(
                new Document("authors", new Document().append("author_id", "1").append("name", "Chetan Bhagat"))
                .append("book_id", "1").append("title", "One Indian Girl").append("isbn", "8129142147")
                .append("price", "$14.99").append("publish_date", format.parse("2016-10-01T00:00:00Z")));

            List < Document > booksList = new ArrayList < Document > ();

            booksList
                .add(new Document("authors", new Document().append("author_id", "2").append("name", "Sarina Singh"))
                    .append("book_id", "2").append("title", "Lonely Planet India").append("isbn", "1743216769")
                    .append("price", "$34.99").append("publish_date", format.parse("2015-10-01T00:00:00Z")));

            booksList.add(new Document("authors", new Document().append("author_id", "3").append("name", "John Keay"))
                .append("book_id", "3").append("title", "India: A History").append("isbn", "0802145582")
                .append("price", "$20.00").append("publish_date", format.parse("2011-04-01T00:00:00Z")));
            // using insertMany
            books.insertMany(booksList);

            MongoCursor < Document > cursor = books.find().iterator();

            try {
                while (cursor.hasNext()) {
                    Document book = cursor.next();
                    System.out.println(book);
                }
            } finally {
                cursor.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            mongoClient.close();
        }
    }
}

Program Output

Document{{_id=57e149628d616c19cc037c75, authors=Document{{author_id=1, name=Chetan Bhagat}}, book_id=1, title=One Indian Girl, isbn=8129142147, price=$14.99, publish_date=Sat Oct 01 00:00:00 IST 2016}}
Document{{_id=57e149628d616c19cc037c76, authors=Document{{author_id=2, name=Sarina Singh}}, book_id=2, title=Lonely Planet India, isbn=1743216769, price=$34.99, publish_date=Thu Oct 01 00:00:00 IST 2015}}
Document{{_id=57e149628d616c19cc037c77, authors=Document{{author_id=3, name=John Keay}}, book_id=3, title=India: A History, isbn=0802145582, price=$20.00, publish_date=Fri Apr 01 00:00:00 IST 2011}}

Shell Output

> use technicalkeeda
switched to db technicalkeeda
> show collections
books
system.indexes
> db.books.find().pretty();
{
        "_id" : ObjectId("57e149628d616c19cc037c75"),
        "authors" : {
                "author_id" : "1",
                "name" : "Chetan Bhagat"
        },
        "book_id" : "1",
        "title" : "One Indian Girl",
        "isbn" : "8129142147",
        "price" : "$14.99",
        "publish_date" : ISODate("2016-09-30T18:30:00Z")
}
{
        "_id" : ObjectId("57e149628d616c19cc037c76"),
        "authors" : {
                "author_id" : "2",
                "name" : "Sarina Singh"
        },
        "book_id" : "2",
        "title" : "Lonely Planet India",
        "isbn" : "1743216769",
        "price" : "$34.99",
        "publish_date" : ISODate("2015-09-30T18:30:00Z")
}
{
        "_id" : ObjectId("57e149628d616c19cc037c77"),
        "authors" : {
                "author_id" : "3",
                "name" : "John Keay"
        },
        "book_id" : "3",
        "title" : "India: A History",
        "isbn" : "0802145582",
        "price" : "$20.00",
        "publish_date" : ISODate("2011-03-31T18:30:00Z")
}
>


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0310 seconds.