AnnouncementIntroducing MongoDB 8.0, the fastest MongoDB ever! Read more >>

Java and MongoDB

Given the popularity of both Java and MongoDB, it is no surprise that they work well together.

Whether you are developing on a local or on-premise MongoDB installation, or going cloud-first with MongoDB Atlas, the MongoDB Java Driver and surrounding ecosystem make it a breeze to integrate MongoDB into your development process.

In this article, we'll dive into the following:

  • Why Use MongoDB with Java?
  • Getting Started with Java and MongoDB
  • Creating Your First Atlas Cluster
  • Connecting to Your Atlas Cluster
  • Documents and Collections
  • CRUD Operations and MQL
  • Integration with Other Technologies
  • Getting Help
  • Frequently Asked Questions

Why Use MongoDB with Java?

Java is one of the most popular programming languages, and with good reason. First released in 1995, Java has maintained a considerable hold on the developer community since. It's a great fit for a number of industries, including financial services, healthcare, and even the public sector. Java is object-oriented and WORA (write once, run anywhere), so it can be run on all platforms that support the language without needing to recompile.

MongoDB holds the top spot as the most popular NoSQL database technology on several lists. It is a document database used to build highly available and scalable internet applications. Founded in 2007, MongoDB has a worldwide following in the developer community. MongoDB has always focused on providing developers with an excellent user experience, which, in addition to all its other features, has made MongoDB a favorite of developers worldwide.

If you're building something new and need a database, consider using MongoDB Atlas from the outset. Atlas will give you a fully-managed, cloud-native database service that comes with a number of features, including full-text search, charts, partner integrations, and much more. If you're building for iOS or Android, Atlas Device Sync makes mobile synchronization a snap. You can even build web applications on GraphQL directly on top of MongoDB Atlas.

Getting Started with Java and MongoDB

Make sure that you have Java 8 (or a later version) installed, and your preferred IDE ready.

The first thing you'll want to do is declare a dependency on the latest version of the MongoDB Java Driver. Instructions for how to do this using either Gradle or Maven, along with example code, can be found here.

Creating Your First Atlas Cluster

Once your Java project dependencies are all set up, you'll need a database.

You can create an account and create a free-tier cluster on MongoDB Atlas by following this guide. It will also show you how to insert sample data.

Connecting to Your Atlas Cluster

After the previous section, you should have a new MongoDB cluster deployed in Atlas, a new database user and password, and some sample datasets loaded into your cluster.

Now, it's time to connect to a database using your driver. In order to establish a database connection, your driver needs instructions on how to connect. These instructions are called the connection string. You can get your connection string for the cluster and username you created in the previous step by going into your Atlas account, navigating to the Database section, and clicking "Connect".

A pop-up will appear prompting you to select your driver and version. Once you've populated both of those drop-downs, you can use the resulting database connection string (it'll begin with "mongdb+srv://") to connect to your cluster. Note that you will need to swap in the values for your own username and password!

You can use this connection string to run queries on your MongoDB cluster from your application. You can find a more in-depth set of instructions as well as example code here.

Documents and Collections

documents in mongodb with java

Unlike SQL databases, MongoDB stores information in documents and collections.

Documents

MongoDB stores data records as BSON documents. BSON is a binary representation of JSON documents, though it contains more data types than JSON. Documents are composed of field-value pairs, with the following structure:

{   
    field1: value1,   
    field2: value2,   
    field3: value3,   
    ...   
    fieldN: valueN
}

The values associated with fields can be any BSON data type, including other documents, arrays, and even arrays of documents. Field names themselves are strings.

Documents are much more flexible than standard rows in relational databases, as they give you a dynamic schema rather than an enforced one (though you can do schema validation with MongoDB if you want!).

Collections

MongoDB stores documents in collections. A collection is like a table in a relational database. For more details on how to create a collection, and other information about collections, you can check out the documentation here.

CRUD Operations and MongoDB Query Language

CRUD (create, read, update, and delete) operations are the four basic operations you might want to do with a database. In the case of MongoDB, you can use CRUD operations to insert documents, to write queries for matching documents, to update documents, and to delete documents. You can do this by using MQL, the MongoDB Query Language. Unlike SQL statements, MQL uses the same syntax as documents, making it intuitive and easy to use for even advanced querying.

A full CRUD tutorial as well as example code for each of the four operations using the Java driver can be found in the MongoDB Developer Center.

Integration with Other Technologies

Chances are, your tech stack is more than just your IDE and your favorite version of Java. Below are just some of the many ways you can use MongoDB.

Spring Data MongoDB

Spring Data MongoDB is part of the umbrella Spring Data project that aims to provide a familiar and consistent Spring-based programming model for new datastores, while retaining store-specific features and capabilities. It provides integration with the MongoDB database, a POJO-centric model for interacting with MongoDB collections, and more.

Cloud Computing Platforms

When it comes to public cloud providers, there are three main providers that come to mind -- Amazon Web Services (AWS), Microsoft Azure, and Google Cloud Platform (GCP). MongoDB Atlas supports all three main cloud service providers. It even supports multi-cloud and multi-region deployments. Learn more here.

Infrastructure Automation

Terraform is an open-source infrastructure as code software tool that enables you to safely and predictably create, change, and improve infrastructure. The HashiCorp Terraform MongoDB Atlas Provider is an official plugin built by HashiCorp that allows you to provision, manage, and control Atlas configurations on any cloud provider using Terraform.

Monitoring Services

Atlas can send metric data about your project to Datadog dashboards or to your Prometheus instance. You can also configure Atlas to send information to Flowdock, Microsoft Teams, OpsGenie, PagerDuty, Slack, and others. You can find more details on this here.

Getting Help

Getting help with java

The best part of using MongoDB is the vibrant Java community that includes users with all levels of experience with the Java driver. The best way to get support for general questions is to use MongoDB Community Forums.

If you're running into an unexpected error, you think you've found a bug in the Java driver, or you have a feature request, please open a JIRA ticket on the JAVA project. You can find instructions on how to do this in the documentation. Bug reports for both the Java driver and the Core Server are public.

Frequently Asked Questions (FAQ)

Is MongoDB a good Java database?

MongoDB is a developer data platform that is compatible with several languages, including Java. MongoDB is a great fit for applications written in Java.

Can I contribute to the Java driver?

We're happy to accept contributions to help improve the driver. We will guide user contributions to ensure they meet the standards of the driver codebase. Please ensure that any PRs include documentation, tests, and pass checks.

What if I want to use SQL?

Please note that support for SQL queries is available as a Preview feature only. You can query a federated database using Atlas SQL. To run queries using the SQL interface, you can connect using the MongoDB JDBC driver (available here) or one of the BI Tool Named Connectors. More details on this Preview feature can be found in the article here.

Can I use POJOs (Plain Old Java Objects) instead of documents?

If you want to use your own Plain Old Java Objects (POJOs) rather than documents, you can use the built-in POJO support that comes with the Java driver. Code examples and a full tutorial can be found here.

Ready to get started?

Use MongoDB in the cloud for free! Register for MongoDB Atlas. No credit card required.