1. Overview
Oct 15, 2019 Simplifying the MongoDB client using BSON codec; Final Code; But to achieve the maximum functionality out of MongoDB, one needs to be familiar with the MongoDB client and in this article, we will discuss just that. Prerequisites for MongoDB Client. In order for this article fully, you will need to first meet the following prerequisites. In this article, we'll have a look at integrating MongoDB, a very popular NoSQL open source database with a standalone Java client. MongoDB is written in C and has quite a number of solid features such as map-reduce, auto-sharding, replication, high availability etc.
In this article, we'll have a look at integrating MongoDB, a very popular NoSQL open source database with a standalone Java client.
MongoDB is written in C++ and has quite a number of solid features such as map-reduce, auto-sharding, replication, high availability etc.
2. MongoDB
Let's start with a few key points about MongoDB itself:
- stores data in JSON-like documents that can have various structures
- uses dynamic schemas, which means that we can create records without predefining anything
- the structure of a record can be changed simply by adding new fields or deleting existing ones
The above-mentioned data model gives us the ability to represent hierarchical relationships, to store arrays and other more complex structures easily.
3. Terminologies
Understanding concepts in MongoDB becomes easier if we can compare them to relational database structures.
Let's see the analogies between Mongo and a traditional MySQL system:
- Table in MySQL becomes a Collection in Mongo
- Row becomes a Document
- Column becomes a Field
- Joins are defined as linking and embedded documents
This is a simplistic way to look at the MongoDB core concepts of course, but nevertheless useful.
Now, let's dive into implementation to understand this powerful database.
4. Maven Dependencies
We need to start by defining the dependency of a Java Driver for MongoDB:
To check if any new version of the library has been released – track the releases here.
5. Using MongoDB
Now, let's start implementing Mongo queries with Java. We will follow with the basic CRUD operations as they are the best to start with.
5.1. Make a Connection With MongoClient
First, let's make a connection to a MongoDB server. With version >= 2.10.0, we'll use the MongoClient:
And for older versions use Mongo class:
5.2. Connecting to a Database
Now, let's connect to our database. It is interesting to note that we don't need to create one. When Mongo sees that database doesn't exist, it will create it for us:
Sometimes, by default, MongoDB runs in authenticated mode. In that case, we need to authenticate while connecting to a database.
We can do it as presented below:
5.3. Show Existing Databases
Let's display all existing databases. When we want to use the command line, the syntax to show databases is similar to MySQL:
In Java, we display databases using snippet below:
The output will be:
Above, local is the default Mongo database.
5.4. Create a Collection
Let's start by creating a Collection (table equivalent for MongoDB) for our database. Once we have connected to our database, we can make a Collection as:
Now, let's display all existing collections for current database:
The output will be:
5.5. Save – Insert
The save operation has save-or-update semantics: if an id is present, it performs an update, if not – it does an insert.
When we save a new customer:
The entity will be inserted into a database:
Next, we’ll look at the same operation – save – with update semantics.
5.6. Save – Update
Let’s now look at save with update semantics, operating on an existing customer:
Now, when we save the existing customer – we will update it:
The database will look like this:
As you can see, in this particular example, save uses the semantics of update, because we use object with given _id.
5.7. Read a Document From a Collection
Let's search for a Document in a Collection by making a query:
It will show the only Document we have by now in our Collection:
5.8. Delete a Document
Let's move forward to our last CRUD operation, deletion:
With above command executed, our only Document will be removed from the Collection.
6. Conclusion
This article was a quick introduction to using MongoDB from Java.
The implementation of all these examples and code snippets can be found over on GitHub – this is a Maven based project, so it should be easy to import and run as it is.
and Transaction Semantics Details with JPA
MongoDB is a NoSQL database that more than a quarter of developers use in some capacity. What makes MongoDB and other NoSQL DBs attractive is flexibility; instead of being held to a rigid schema that scales vertically, you can evolve your schema as you grow and scale horizontally. MongoDB went public in 2017 and is worth more than $17 billion today.
Document DBs work through nested key-value pairs instead of relational tables and columns. You’re going to need to parse data for your front-end eventually, and with document DBs, your data is already stored in the right format (give or take a .map or .reduce). Working with MongoDB through the command line isn’t exactly a cakewalk: This post will walk through the best MongoDB GUIs available for reading from and writing to your MongoDB clusters.
The Mongo Shell Versus a MongoDB GUI
The most basic way to access MongoDB is through the mongo
shell; you can use it to query, update data, and complete admin tasks.
It’s included in the MongoDB Server installation, so you’re all set as long as you’re comfortable with shell commands. Traversing objects and writing long queries in the command line can get annoying fast, so using the shell is usually best for quick peeks or admin tasks.
It’s definitely possible to query your Mongo data exclusively from the command line, but if you’re working with even medium-sized datasets, GUIs offer a helpful alternative.
MongoDB GUIs provide a user interface for your MongoDB database that gives you the ability to visualize data and edit queries without the use of shell commands (or with them — more on that later).
The best MongoDB GUIs share similar features:
- A visual query editor: Click or drag-and-drop elements to create queries.
- Query autocomplete: Auto-suggestions for collections, fields, methods, and operators.
- An aggregation framework: Build queries out step-by-step, test along the way, then export into usable code.
- Server and query analytics: Insights into query and server performance.
- Relational database to MongoDB data transfer: Automate tedious and error-prone data transfers between database types.
Below is a list of the best MongoDB GUIs that 2021 has to offer. Each one has features that set it apart from the rest. The best one for you will depend on the scope of your project, the features you need, and your budget.
MongoDB Compass
(Image courtesy of MongoDB Compass GitHub Repository)
Overview
The creators of MongoDB (Mongo) have their own GUI called Compass. It’s platform-agnostic and provides a graphical view of your database without the need to use a query language. MongoDB recently announced that the fully featured Compass GUI is completely free for everyone to use. Plus, the repo is now open-source on GitHub.
Some notable MongoDB Compass features include:
- Schema visualization: Compass visually displays your collections to help you better understand your datasets.
- CRUD visual editor: Perform CRUD operations within the UI, no need to type queries.
- Geospatial data: Create queries on map data using an intuitive UI with generated results in both graph and JSON document form.
- Validation: Write JSON Schema validation rules using an editor that suggests BSON data types and validation keywords as you write
Winning feature: Compass Plugins
One of the best features of the MongoDB Compass GUI is that it has an API for adding plugins. The Compass community has built tons of cool plugins that can generate data for testing, inspect database users, and even check the shard status of the database. If there’s a feature you want but a plugin isn’t available yet, you can build your own using their plugin template.
TablePlus
(Image courtesy of TablePlus)
Overview
TablePlus is a modern, native GUI tool for relational databases like MySQL, PostgreSQL, SQLite, and NoSQL databases like MongoDB. The TablePlus team consists of founder Henry Pham and Windows developer Raccoon Thai. The team, as well as the community, is also fairly active on GitHub.
Some notable TablePlus features include:
- Customizable UI: There’s no need to turn to Mojave. With TablePlus, you can customize your configurations and their appearance
- In-line edits: Edit data rows and table structure with a single click
Winning feature: database security
Mongo Client Java
TablePlus promises secure connections. The connection between you and your database is end-to-end encrypted –– no data is sent to a TablePlus server. Additionally, TablePlus ensures database credentials are stored securely in your device’s keychain and comes with built-in SSH. TablePlus also supports multi-step authentication and native libssh.
Robo 3T
(Photo courtesy of Robo 3T blog)
Overview
Mongo Client Install
Robo 3T is an open-source, platform-agnostic, lightweight GUI for MongoDB. Formerly known as Robomongo, the company was bought in 2017 by 3T Software Labs and rebranded (Robo 3T also made it open source).
The project continues to be developed and has 8K stars on Github. In that vein, one of the best parts of using this GUI is the large community of users. Loads of tutorials, guides, and forums are available if you get stuck – just search.
Some notable Robo 3T features include:
- Code autocomplete: While Robo 3T doesn’t have the autocompleting prowess of IntelliShell (see Studio 3T below), it does have a useful runtime autocomplete feature that works through an internal virtual machine.
- Fast UI: All operations are done asynchronously, which means the application will never block you from working by freezing up.
Winning feature: embedded Mongodb shell
Many of the MongoDB GUIs have emulatedmongo
shells, but this GUI has an embeddedmongo
shell. The embedded shell provides increased functionality over an emulated shell because emulators generally run on top of a provided API, whereas an embedded shell works directly with MongoDB.
Subscribe to the Retool monthly newsletter
Once a month, we send out top stories (like this one) along with Retool tutorials, templates, and product releases.
Studio 3T
(Photo courtesy of Studio 3T)
Overview
Studio 3T, formerly MongoChef, is the robust, professional version of Robo 3T owned by the same parent company, 3T Software Labs. Studio 3T is more than just a MongoDB GUI: it’s also an IDE and client. There is no free version of this software (unless you count Robo 3T), and the Core pricing level starts at $149/year per user. Even then, the Core level lacks features that pricier ones have, like SQL import/export, SQL queries, and the schema explorer.
Some notable Studio 3T features include:
- IntelliShell: A smart, built-in
mongo
shell with autocomplete that supports Javascript standard library functions, collection and field names, operators, and methods. - Three ways to view data: Once you have retrieved your data from the database, you can view it in three different formats:
- Table View formats the data into rows and columns.
- Tree View formats the data into expandable hierarchies.
- JSON View formats your data as JSON documents.
- Code generation: Export queries into Node.js, Python, Java, C#, PHP, Ruby, or the
mongo
shell language. - Data import: Support for data imports from SQL databases, Oracle, and Sybase.
Winning feature: four ways to query MongoDB and view data
Out of all MongoDB GUIs, Studio 3T provides the most ways to query your database. You can query using:
- SQL queries: Query MongoDB using the SQL query language (super cool!)
- The
mongo
shell: Built-in IntelliShell technology that provides robust autocomplete features - The Aggregation Editor: For building up complicated queries
- The Visual Query Builder: A drag-and-drop editor for building out queries (fun fact: can be used side-by-side with IntelliShell)
Given this volume of query methods (including less “technical” ones), Studio 3T is usable for anyone, no matter their familiarity with document-based databases, query languages, or command lines.
NoSQLBooster
Overview
NoSQLBooster is a shell-centric GUI with a broad range of features that come with a paid license. The free tier is missing many of the features that make this GUI so great, like code completion and the visual query builder. NoSQLBooster does not work through a subscription model, so once you pay for a license, it’s yours forever (or until you want to update your version).
Some notable NoSQLBooster features include:
- IntelliSense: Similar to Studio 3T’s IntelliShell, this language service appears as a tooltip while you type to suggest completions, methods, properties, variables, keywords, collection names, field names, and operators.
- Interactive samples: In-app tutorials with prewritten queries and descriptions for learning how to use MongoDB.
A notable part of IntelliSense is the built-in snippets that offer code completion for operations like SQL to MongoDB data conversions and date ranges. You can also create your own snippets to save time.
Winning feature: NPM packages in the MongoDB shell script
The best feature of NoSQLBooster is the unique ability to add any NPM package into the MongoDB shell script. In fact, this GUI already comes with a number of useful and popular utility modules — like lodash, moment, bluebird, ShellJS, and math.js — in the global scope, ready to use.
HumongouS.io
(Image courtesy of HumongouS.io)
Overview
HumongouS.io is a fully online MongoDB GUI. Since it’s online, HumongouS.io allows users to collaborate pretty seamlessly. Instead of using it as just a GUI, you can set it up as a more fully-featured internal admin tool. You then don’t need to share database credentials but can instead invite people to collaborate with you from the app. You can even access your data on a mobile device.
Some notable features include:
- Smart filters: Create filters that you can use to display your collections as chips, which enables quick access
- Charts and dashboards: Easily create charts and dashboards to track the metrics that are important to you
Winning feature: widgets for customization
With HumongouS.io widgets, you can customize how your data displays and use those widgets to pull data from specific reference collections as needed. There are viewer, form, and layout widgets. Viewer widgets let you represent data in more meaningful ways than default string values.
Form widgets are, according to HumongouS.io’s documentation, “the building blocks of forms.” They’re also customizable, meaning you can match them to any data type in your database.
Layout widgets give you an alternative to the default table view, allowing you to display specialized data.
NoSQL Manager
(Image courtesy of NoSQL Manager)
Overview
NoSQL Manager is a shell-based MongoDB GUI tool. NoSQL Manager makes it easy to navigate, view, and edit documents, as well as set limits to maximize performance. You can manage, as the name implies, a lot of things, including collections and their indices as well as users, roles, and functions. It offers support for MongoDB Enterprise, MongoDB on Azure Cosmos DB, and Amazon DocumentDB.
Some notable features include:
- Wide support: NoSQL Manager supports replica sets, sharded clusters connections, and standalone hosts
- Document viewer: The NoSQL Manager document viewer and editor offer Tree, Table, and JSON view modes
- SSH tunneling: NoSQL Manager offers SSH tunneling for MongoDB connections
- Imports: Import tables from your MySQL and SQL Server databases
Winning feature: autocompletion
NoSQL Manager comes with a MongoDB UI Shell that offers code autocompletion, syntax highlighting, and hints. Autocompletion takes much of the guesswork out of MongoDB management, helping you by autocompleting things like the collection names and methods in MongoDB Shell commands. As you type into the Shell, NoSQL Manager uses context clues to provide collection or method completion.
Bonus: Retool
Overview
Retool is a low code app builder where you can build any GUI for MongoDB (see template). Retool makes it possible to drag-and-drop visual components to avoid boilerplate code and connect to anything with a REST or GraphQL API, meaning you can build a full-featured MongoDB GUI—and include any CRUD operations—in just a few hours.
Some notable Retool features include:
Mac Os Mongo Client
- Speed: Connecting Retool to MongoDB takes just a few minutes
- Schema inspection: Visually view your data.
- Save and share queries: Keep your queries handy for multiple uses.
- Turn your queries into useful tools: go from query to table, search, and button without writing frontend code.
Winning feature: Customizable front end for visualizing data
You can use Retool’s pre-built components—including tables, buttons, text inputs, and search bars—to not only view your data but do any CRUD operations you need to keep your business going. Once you connect your data sources, you design your frontend with their drag-and-drop component tool.
The Best MongoDB GUI for Your Project
Mongodb Client
As with any tool, the best MongoDB GUI for you depends on what you’re trying to accomplish.
If you want to completely avoid the command line, MongoDB’s Compass is probably the most fully featured and natively integrated GUI out there. If you want a simple application that has a well-supported community, Robo 3T is the best GUI. If you’re familiar with SQL and want to keep writing queries in everyone’s favorite query language™, NoSQLBooster is going to feel slick. If you’re looking to easily share queries or turn your queries into tools, check out Retool.