Connect to MongoDB and Perform CRUD using Java

  •        0

We aggregate and tag open source projects. We have collections of more than one million projects. Check out the projects section.

MongoDB is a popular and widely used open source NoSQL database. MongoDB is a distributed database at its core, so high availability, horizontal scaling, and geographic distribution is quite possible. It is licensed under Server Side Public License. Recently they moved to Server Side Public License, before that MongoDB was released under AGPL.   This article will provide basic example to connect and work with MongoDB using Java.

Basic Concepts

It is document oriented aggregate database which stores and retrieve json documents. Mongo database stores data like key-value pairs(json structure) as a document. Each document is implicitly comes with _id key also.

Eg: Customer json document (i.e. customer record) will look like with _id key value

"_id" : ObjectId("5c376af48ece577520371dce"),
"firstName" : "Nagappan",
"lastName": "Subramanian",
"emailid": ""


Set of document are available in a collection. Group of collections reside in database. It is schemaless database so any new key can be added on the fly there is no need to do any special work like changing the metadata like RDMS. If customer collection requires new field mobile number, mongo will accept the data with mobile number without any prework or setup.

Java Driver Options

MongoDB jar driver("mongo-java-driver") is legacy uber jar which is not java 9 compliant and it is also deprecated. To connect to MongoDB programatically (“mongodb-driver-sync”) would be best suitable and supported jar. 


Database Installation & Setup

Download MongoDB installer based on your operating system and installer takes though the wizard with simple primitive steps. It will install as a service which mostly available in port 27017. It can also be checked through following command.

      tasklist | grep mongo


Create a simple project from maven archetype template.

      mvn archetype:generate -DgroupId=com.nagappans.core -DartifactId=javamongodb


Add mongo java driver as dependency in pom.xml


Let's try to save and retrieve below Customer model.

      import org.bson.types.ObjectId;
      public final class Customer {
         private ObjectId id;
         private String firstName;
         private String lastName;
         private String emailId;

          public ObjectId getId() {
                   return id;

          public void setId(ObjectId id) {
        = id;

          public String getFirstName() {
                 return firstName;

          public void setFirstName(String firstName) {
               this.firstName = firstName;

          public String getLastName() {
                return lastName;

         public void setLastName(String lastName) {
               this.lastName = lastName;

         public String getEmailId() {
              return emailId;

        public void setEmailId(String emailId) {
              this.emailId = emailId;

         public String toString() {
              return "Customer{" + "id=" + id + ", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' + ", emailId='" + emailId + '\'' + '}';

Connect to MongoDB

Now to connect the mongo database, build the client settings with connection strings, then create mongo client which connects to the mongo database.

  MongoClientSettings mongoClientSettings = MongoClientSettings.builder()
                                .applyConnectionString(new ConnectionString("mongodb://localhost:27017"))
                                .credential(MongoCredential.createCredential("username", "auth-dbname",

          MongoClient mongoClient = MongoClients.create(mongoClientSettings);

          MongoDatabase mongoDatabase = mongoClient.getDatabase("customer-database");
          MongoCollection<Customer> collection = mongoDatabase.getCollection("customer");

In old legacy jar("mongo-java-driver"), connecting to MongoDB will look as below.

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


Save document to database

Create a customer object and use the collection method to persist the record.

       Customer customer1 = new Customer("Rajesh", "Kannan", "");


If you want to insert documents in to batches then below code can be used to insert list of documents.

         List<Customer> customerList = new ArrayList<Customer>(); 
         customerList.add(new Customer("user", "one", ""));
         customerList.add(new Customer("user", "two", ""));
         customerList.add(new Customer("user", "three", ""));

Read data from Database

Data can be accessed from database in two ways. One way is to get the data as Json and map it your model class or register the model with Codec Registry, which will convert document to respective model . 


Retrieve data as JSON

            MongoDatabase mongoDatabase = mongoClient.getDatabase(dbname);
            MongoCollection<Document> collection = mongoDatabase.getCollection("customer");
            collection.find().forEach(new Consumer<Document>() {
                  public void accept(Document customer) {


Retrieve data directly as POJO

           private CodecRegistry getPojoCodecRegistry() {
                    return fromRegistries(MongoClientSettings.getDefaultCodecRegistry(),

           MongoClientSettings mongoClientSettings = MongoClientSettings.builder()
                                           .applyConnectionString(new ConnectionString(connectionSting))

          MongoClient mongoClient = MongoClients.create(mongoClientSettings); 

           MongoDatabase mongoDatabase = mongoClient.getDatabase("customer-database");

           MongoCollection<Customer> collection = mongoDatabase.getCollection("customer", Customer.class);
           collection.find().forEach(new Consumer<Customer>() {
                     public void accept(Customer customer) {


Update document

Once created document can be updated by various methods like updateOne, updateAll, findAndUpdate. Below is example of changing only one record having expected firstname will be changed.

          collection.updateOne(eq("firstName", "Rajesh"), set("firstName", "Soniya"));

Delete document

Document can be deleted by having any filter parameter or delete many documents in collections.

           collection.deleteOne(eq("firstName", "Soniya"));


Customized querying the document

Customer collection can be searched similar to rdms against all fields with flexibility of querying the data. Below code snippet search for customer's first name starting with r.

             collection.find(Filters.regex("firstName", "r")).forEach(new Consumer<Customer>() {
                             public void accept(Customer customer) {


All the above code snippets are enclosed in a project and available in below github repo.




Nagappan is a techie-geek and a full-stack senior developer having 10+ years of experience in both front-end and back-end. He has experience on front-end web technologies like HTML, CSS, JAVASCRIPT, Angular and expert in Java and related frameworks like Spring, Struts, EJB and RESTEasy framework. He hold bachelors degree in computer science and he is very passionate in learning new technologies.

Subscribe to our newsletter.

We will send mail once in a week about latest updates on open source tools and technologies. subscribe our newsletter

Related Articles

Advanced Programming Guide in Redis using Jedis

  • redis jedis advanced-guide cluster pipline publish-subscribe

Redis is an in-memory data structure store, used as a database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes with radius queries and streams. This blog covers the advanced concepts like cluster, publish and subscribe, pipeling concepts of Redis using Jedis Java library.

Read More

An introduction to MongoDB

  • mongodb database document-oriented-databse no-sql c++ data-mining

MongoDB is the most exciting SQL-free database currently available in the market. The new kid on the block, called MongoDB is a scalable, high-performance, open source, schema free and document oriented database that focuses on the ideas of NoSQL Approach. Written in C++, it has taken rapid strides since its emergence into the public sphere as a popular way to build your database applications.

Read More

An Introduction to the UnQLite Embedded NoSQL Database Engine

  • database nosql embedded key-value-store

UnQLite is an embedded NoSQL database engine. It's a standard Key/Value store similar to the more popular Berkeley DB and a document-store database similar to MongoDB with a built-in scripting language called Jx9 that looks like Javascript. Unlike most other NoSQL databases, UnQLite does not have a separate server process. UnQLite reads and writes directly to ordinary disk files. A complete database with multiple collections is contained in a single disk file. The database file format is cross-platform, you can freely copy a database between 32-bit and 64-bit systems or between big-endian and little-endian architectures.

Read More

Quick Start Programming Guide for redis using java client Jedis

  • redis jedis redis-client programming database java

Redis is an open source (BSD licensed), in-memory data structure store, used also as a database cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes with radius queries and streams. This article explains about how to communicate with Redis using Java client Jedis.

Read More

Cache using Hazelcast InMemory Data Grid

  • hazelcast cache key-value

Hazelcast is an open source In-Memory Data Grid (IMDG). It provides elastically scalable distributed In-Memory computing, widely recognized as the fastest and most scalable approach to application performance.&nbsp;Hazelcast makes distributed computing simple by offering distributed implementations of many developer-friendly interfaces from Java such as Map, Queue, ExecutorService, Lock and JCache.

Read More

Exonum Blockchain Framework by the Bitfury Group

  • blockchain bitcoin hyperledger blockchain-framework

Exonum is an extensible open source blockchain framework for building private blockchains which offers outstanding performance, data security, as well as fault tolerance. The framework does not include any business logic, instead, you can develop and add the services that meet your specific needs. Exonum can be used to build various solutions from a document registry to a DevOps facilitation system.

Read More

LogicalDOC - Open Source DMS

  • dms document-management-system

LogicalDOC is both a document management and a collaboration system. The software is loaded with many functions and allows organizing, indexing, retrieving, controlling and distributing important business documents securely and safely for any organization and individual.

Read More

MailHog - Web and API based SMTP testing

  • smtp-testing testing-tool smtp test automation email-server email

Most of the projects will have a requirement of sending and receiving mails. We have mentioned about GreenMail - Email Test Framework, in our previous article about API based SMTP testing. In this article, we discuss about MailHog - Web and API based SMTP testing. You send out a mail from your code and you can check it via web visually and also via API. Those who do API testing can check via API. Developers may want to visually verify the format of the mail. MailHog is a best bet for SMTP testing.

Read More

WebSocket implementation with Spring Boot

  • websocket web-sockets spring-boot java

Spring Boot is a microservice-based Java framework used to create web application. WebSocket API is an advanced technology that provides full-duplex communication channels over a single TCP connection. This article explains about how to implement WebSocket using Spring Boot.

Read More

Is ZooKeeper mandatory for Cloud

  • zookeeper distributed cloud

Cloud is nothing but more than one system or application distributed across the network, across the globe. It may have couple of application servers, database server, shared data storage, backup server and lot more. The resources in the distributed environment must have information about each other so that they could co-ordinate and share without any issues. ZooKeeper helps to do that.

Read More

Light4j Cookbook - Rest API, CORS and RDBMS

  • light4j sql cors rest-api

Light 4j is a fast, lightweight and cloud-native microservices framework. In this article, we will see what and how hybrid framework works and integrate with RDMS databases like MySQL, also built in option of CORS handler for in-flight request.

Read More

Advantages and Disadvantages of using Hibernate like ORM libraries

  • database orm

Traditionally Programmers used ODBC, JDBC, ADO etc to access database. Developers need to write SQL queries, process the result set and convert the data in the form of objects (Data model). I think most programmers would typically write a function to convert the object to query and result set to object. To overcome these difficulties, ORM provides a mechanism to directly use objects and interact with the database.

Read More

How to learn from open source projects

  • open-source learning methodology

Students ask this question frequently steps or methodology to learn from open source projects. There is no single answer or steps available. I listed the steps which i follow and i hope this will help for few.

Read More

Best open source Text Editors

  • text-editor editor tools dev-tools

Text editors are mainly used by programmers and developers for manipulating plain text source code, editing configuration files or preparing documentation and even viewing error logs. Text editors is a piece of software which enables to create, modify and delete files that a programmer is using while creating website or mobile app.In this article, we will discuss about top 7 all-round performing text editors which is highly supportive for programmers.

Read More

Data dumping through REST API using Spring Batch

  • spring-batch data-dump rest-api java

Most of the cloud services provide API to fetch their data. But data will be given as paginated results as returning the complete data will overshoot the response payload. To discover the complete list of books or e-courses or cloud machine details, we need to call the API page-wise till the end. In this scenario, we can use Spring Batch to get the data page by page and dump it into a file.

Read More

Thymeleaf - Text display, Iteration and Conditionals

  • thymeleaf template-engine web-programming java

Thymeleaf is a server-side Java template engine for both web and standalone environments. It is a better alternative to JavaServer Pages (JSP). Spring MVC and Thymeleaf compliment each other if chosen for web application development. In this article, we will discuss how to use Thymeleaf.

Read More

Getting started with Apache OpenNLP

  • apache-opennlp machine-learning java nlp natural-language-processing

The Apache OpenNLP library is a machine learning based toolkit for the processing of natural language text. OpenNLP also includes entropy and perceptron based machine learning. . It contains several components for natural language processing pipeline like sentence detector, tokenizer, name finder, document categorizer, part-of-speech tagger, chunker, parser, co-reference resolution.

Read More

Introduction to Light 4J Microservices Framework

  • light4j microservice java programming framework

Light 4j is fast, lightweight, secure and cloud native microservices platform written in Java 8. It is based on pure HTTP server without Java EE platform. It is hosted by server UnderTow. Light-4j and related frameworks are released under the Apache 2.0 license.

Read More

Introduction to Apache Cassandra

  • cassandra database nosql

Apache Cassandra was designed by Facebook and was open-sourced in July 2008. It is regarded as perfect choice when the users demand scalability and high availability without any impact towards performance. Apache Cassandra is highly scalable, high-performance distributed database designed to handle large voluminous amounts of data across many commodity servers with no failure.

Read More

Lucene Vs Solr

  • searchengine lucene solr

Lucene is a search library built in Java. Solr is a web application built on top of Lucene. Certainly Solr = Lucene + Added features. Often there would a question, when to choose Solr and when to choose Lucene.

Read More

We have large collection of open source products. Follow the tags from Tag Cloud >>

Open source products are scattered around the web. Please provide information about the open source projects you own / you use. Add Projects.