Close

MongoDb - Getting Started with Java

[Updated: Mar 13, 2019, Created: Mar 9, 2019]

MongoDB is a NoSQL database. It provides high performance, high availability, and automatic scaling features.

A record in MongoDB is a document, which is a data structure composed of field and value pairs.

MongoDB documents are written in BSON (Binary JSON) which is similar to JSON format, for example

{
 name: "Tina",
 dept: "IT",
 phones: [ "111-111-111", "222-222-222" ]
}

Installing MongoDB

In this tutorial we are going to use local 'MongoDB Community Edition' (Open source). Follow this guide to install community edition.

After installation make sure the mongoDB local server is running, and a database (say 'my-database') and a collection (say 'test-collection') have been created.

Connecting MongoDB and performing operations in Java

MongoDB can be connected from many programming languages. For each language there's MongoDB driver, which follows the MongoDB specifications. Check out the list of available MongoDB drivers.

In this example we are going to use Java driver in a maven project.

pom.xml

<project .....>
<modelVersion>4.0.0</modelVersion>

<groupId>com.logicbig</groupId>
<artifactId>mongodb-getting-started-with-java</artifactId>
<version>1.0-SNAPSHOT</version>

<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>3.10.1</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>11</source>
<target>11</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>

Inserting a document

package com.logicbig.example;

import com.mongodb.client.*;
import org.bson.Document;

public class InsertDocumentExample {
  public static void main(String[] args) {
      MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
      MongoDatabase database = mongoClient.getDatabase("my-database");
      //A collection is equivalent to RDBMS table
      MongoCollection<Document> collection = database.getCollection("test-collection");
      //inserting a document
      Document doc = new Document()
              .append("name", "Joe")
              .append("dept", "IT")
              .append("phone", "111-111-111");
      collection.insertOne(doc);
  }
}

Querying documents

package com.logicbig.example;

import com.mongodb.client.*;
import org.bson.Document;

public class QueryCollectionExample {
  public static void main(String[] args) {
      MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
      MongoDatabase database = mongoClient.getDatabase("my-database");
      MongoCollection<Document> collection = database.getCollection("test-collection");

      //query collection
      //finding all
      FindIterable<Document> documents = collection.find();
      for (Document document : documents) {
          System.out.println(document.toString());
      }
  }
}
Document{{_id=5c85ff9aef4200489b0d8fc2, name=Joe, dept=IT, phone=111-111-111}}

Example Project

Dependencies and Technologies Used:

  • mongodb-driver-sync 3.10.1: The MongoDB Synchronous Driver.
  • JDK 11
  • Maven 3.5.4

MongoDb + Java Getting started Select All Download
  • mongodb-getting-started-with-java
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • InsertDocumentExample.java

    See Also