MongoDB Compass Installation and Usage
For installing the GUI of MongoDB and MongoDB Compass on Ubuntu 22.04 system, you will have to perform the following steps:
Step # 1: Updating the System Index:
First, you need to update your system’s index with the command given below:
Step # 2: Downloading MongoDB Compass on Ubuntu 22.04:
Once your system’s index has been updated successfully, you need to download the “.deb” file of MongoDB Compass by running the following command or you can even download it from the official site of MongoDB manually.
When this command will finish its execution, the output shown below will be presented to you:
Step # 3: Installing MongoDB Compass on Ubuntu 22.04:
Then, you can install MongoDB Compass on your Ubuntu 22.04 system with the help of the following command:
Upon a successful installation of the MongoDB Compass on Ubuntu 22.04, the output shown below will appear on the terminal:
Usage of MongoDB Compass on Ubuntu 22.04:
Before starting to use the MongoDB Compass, you need to ensure that the MongoDB server is running on your Ubuntu 22.04 system. Otherwise, you will not be able to connect to the MongoDB database. Eventually, you will not be able to work with the MongoDB Compass. You can run the MongoDB server by executing the “mongo” command in your system’s terminal. Once the MongoDB server starts running on your system, you can carry out the following steps:
Step # 1: Launching MongoDB Compass on Ubuntu 22.04:
You can launch the MongoDB Compass by looking for it in the Application Menu’s search bar of your Ubuntu 22.04 system and clicking on the relevant search result. The welcome interface of the MongoDB Compass tool is shown in the image below:
When you close the welcome message dialogue box, you will be presented with the Privacy Settings dialogue box as shown in the following image. From here, you need to click on the Start Using Compass button for proceeding further.
Step # 2: Connecting to the MongoDB Database in Ubuntu 22.04:
Now, you need to connect to the MongoDB database. For that, you will have to type in your Local Host Address in the space provided and click on the Connect button as shown in the image below:
Step # 3: Creating a Database and a Collection in MongoDB Compass:
After connecting to the MongoDB database, you can create a database and a collection in MongoDB Compass very easily. You should click on the Databases tab for creating a new database.
Here, all the three default databases will be presented to you. You can create a new one by clicking on the Create database button.
Upon clicking this button, you will be asked to type in the name of your database as well as the name of the collection that you want to create inside this database (you can even create more collections inside the same database later). After providing the names of the database and the collection, you have to click on the Create Database button as shown below:
Step # 4: Inserting a Document in the Collection in MongoDB Compass:
Now, you will be able to see your newly created database within the list of MongoDB databases. For inserting a document inside the newly created collection in your MongoDB database, you first need to expand the database tab by clicking on the name of your particular database as highlighted in the following image:
From here, you need to click on the name of your specific collection as shown below:
Once you are inside your new collection, you need to click on the ADD DATA button and then select the Insert Document option.
After doing this, you will be presented with a sample document as shown in the following image:
You can remove this sample document and add your own as shown in the image below. In the same manner, you can even insert multiple documents at a time separated from each other by commas. You need to be careful about the syntax of the query. After inserting the document[s], you have to click on the Insert button.
Now, you will be able to see the inserted document[s] inside your collection as shown below:
Step # 5: Deleting the Document in the Collection in MongoDB Compass:
For deleting a document, you need to hover over it and then click on the remove icon as highlighted in the following image:
Then, you need to confirm its deletion by clicking on the DELETE button.
Step # 6: Deleting the Collection in MongoDB Compass:
Finally, click on the three dots located with its name and then select the Drop Collection option.
After that, you can provide the confirmation by clicking on the Drop Collection option highlighted in the image shown below:
This guide was primarily written to deliver two functions: the installation of MongoDB Compass and the use of MongoDB Compass on Ubuntu 22.04. We first talked about the installation of this tool on Ubuntu 22.04 by explaining each. It is followed by the very basic usage of this tool. By following this tutorial, you will easily be able to use MongoDB Compass for creating a database and a collection, inserting documents inside a collection, deleting documents from a collection, and deleting a MongoDB collection.
About the author
Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.
MongoDB Compass is a GUI based tools (unline MongoDB Shell) to interact with local or remote MongoDB server and databases. Use Compass to visually explore your data, run ad hoc queries, perform CRUD operations, and view and optimize your query performance. It can be installed on Linux, Mac, or Windows.
If you have not installed MongoDB Compass with the MongoDB, then download the free community version of Compass for your platform from here.
Now, do a window search on "mongodb compass" and open it, as shown below.
On the main page, click on the New Connection tab on the left pane to open New Connection page shown above. You can paste a connection string or click on Fill in connection fields individually link. This will open the following window where you can enter the host name, port, username, password, etc.
This already has default parameters, just click OK to connect with your local server, as shown below.
As you can see above, it will display all the databases on the connected MongoDB server. On the left pane, it displays information about the connected server.
Now, you can create, modify, delete databases, collections, documents using MongoDB Compass. Click on the CREATE DATABASE button to create a new database. This will open Create Database popup, as shown below.
MongoDB Compass — Create Database
Enter your database name and collection name and click Create Database . This will create a new database humanResourceDB with the new employees collection shown below.
MongoDB Compass — Collections
Click on employees collection to insert, update, find documents in it. This will open the following window to manage documents.
MongoDB Compass — Manage Documents
Data in MongoDB has a flexible schema. Collections do not enforce a rigidly-defined document structure and the schema of a collection is not defined or available for inspection within the database. MongoDB’s flexible schema and rich document structure make developers more productive, but they also make it difficult to explore and understand the underlying data and its structure without first executing queries in the shell against the database.
MongoDB Compass is a tool designed to allow users to easily analyze and understand their schema within MongoDB without having to connect to a shell or be familiar with the query syntax. It provides users with a graphical view of their MongoDB schema by randomly sampling a subset of documents from the entire collection. By sampling a subset of documents, MongoDB Compass has minimal impact on the performance of the database and can produce results to the user very quickly. For more information on sampling, see the Frequently Asked Questions section.
MongoDB Compass currently runs on Mac OS X and Windows. Software requirements to run Compass are listed below:
|Platform||Mac OS X||Windows||Linux|
On Windows, Compass also requires .NET 4.5+.
To download Compass, see the downloads page.
Installing on OS X¶
The Compass package is downloaded as a .dmg disk image. After the download, open the disk image and drag the Compass application to the Applications folder.
The installation is now complete and the disk image can be safely unmounted. Compass can be launched from the Applications directory.
Installing on Windows¶
The Compass setup application is downloaded as a .exe executable file. Run the program to begin the setup process, which will automatically install Compass.
Compass requires the Microsoft .NET Framework version 4.5 or later. If it is not already installed on the system, the setup program will prompt to automatically install .NET.
Run and connect to MongoDB¶
When Compass is run for the first time, it presents the following initial connection dialog:
The following information is requested:
- Hostname: The hostname of the machine where mongod is running.
- Port: The port of the machine where mongod is running.
- Authentication: The authentication mechanism to connect to the target host. Supported authentication mechanisms include:
- SSL: Whether or not Compass should connect to the target host with SSL. Several SSL options are available:
- Unvalidated: If this option is used, the server cerficiate is not validated and no client certificate will be provided. The server must be set up to allow connections without valid certificates.
- Server Validation: The server certificate will be validated, but no client certificate will be provided. The server must be set up to allow connections without valid certificates.
- Server and Client Validation: The server certificate will be validated and a client certificate must be provided.
- Favorite Name (Optional): A nickname for the connection. Previous connections are saved in Compass; a descriptive name simplifies re-establishing the connection on future runs.
After providing the requested information, click “Connect” to launch the main Compass window.
Select a database and collection¶
Use the navigation pane to select a database and collection to analyze.
After making a selection, Compass will begin analyzing documents and present a summary screen. Below is an example; results will vary based on the contents of the collection.
Types and Missing Fields¶
Compass displays the data types of fields in a collection’s schema. The example below reports that there are documents in the collection that contain a field last_login with the type date :
Compass also displays a percentage breakdown for fields with varying data types across documents. In this example, 81% of documents store phone_no as a string , and the remaining 19% store it as a number :
For sparse fields, where some documents omit a value, Compass displays the percentage of missing values as undefined . Here, the age field is missing in 40% of the sampled documents.
Compass displays different charts for data fields depending on their BSON type.
Strings can be displayed in three different ways. If all the documents in the collection have unique strings for a given field, Compass will display a random selection of string values. Click on the refresh icon to generate a new set of random strings sampled from the values for that field.
If there are only a handful of unique string values, Compass will show the strings in a single graded bar, indicating the percentage breakdown of string values.
When there are many different string values with some duplication, Compass displays a histogram indicating the frequency of each string found for that field. Hover the mouse on each histogram bar to see a tool tip indicating the value of the string.
Numbers are displayed in a similar manner to strings. A randomly-sampled subset of data is shown for an entirely unique data set.
For a data set of numbers containing duplicates, a histogram is shown to indicate frequency.
Sub-document fields are displayed with a small triangle next to the field name, along with some additional data.
Click on the triangle to expand the field and view the sub-documents contained within.
Fields containing an array are displayed with the type distribution of the array’s elements. A second type distribution bar is displayed beneath the array type.
Click on an array sub-type to view a chart of the data for that specific type.
Dates and ObjectIDs¶
Bar charts are used to represent dates. They are also used for fields containing an ObjectID, from which a date can be extracted.
The two charts on the top row visualize the date’s data: the first is the day of the week of the timestamp, and the second is the hour of day. The third chart in the bottom row displays the range of timestamps: the earliest date, the most recent date and the distribution of all timestamps in between.
When Compass detects values that look like geographical coordinates, it displays the data in a scatter plot. Both GeoJSON documents and legacy coordinate pairs are supported.
Hover over points in the scatter plot with the mouse cursor to see a tooltip displaying latitude and longitude coordinates.
When a field has mixed types throughout a collection, the type of chart displayed can be changed by clicking on a specific data type underneath the field name.
As an example, this phone_no field is a mix of strings and numbers. The chart displayed shows the values that are strings.
Click on the number data type to view the values that are numbers instead.
There are two methods of building queries in Compass: automatic generation with the query builder, or manual entry in the query bar.
Using the Query Builder¶
Select values from charts¶
Charts in Compass are fully interactive. Clicking on a chart value or bar will automatically build a MongoDB query that matches the documents pertaining to that section of the chart.
In the example below, clicking on the “JFK” bar builds a query matching all documents whose departureAirportFsCode field matches “JFK”.
Clicking on other field values adds them to the selection, creating a more complex query.
Continuing with the example, this selects a particular flightId in addition to departures from JFK Airport.
To select multiple values within the same field, click and drag the mouse over a selection of values. Alternatively, hold the Shift key while selecting the desired values.
To deselect a previously-selected value, hold the Shift key while clicking on the selection.
Apply the query¶
After building a query, run it by clicking the Apply button. To clear the query, use the Reset button.
Note that composing “OR” queries is not yet possible with the automatic query builder.
In addition to the automatic query builder, queries can be manually entered into the query bar. It is also possible to manually edit queries built from the automatic query builder for further refining.
Enter a query in the query bar¶
Queries entered in the query bar must be valid MongoDB syntax. Only finds will be executed.
This example manually selects documents whose departureAirportFsCode is “JFK”.
When a valid query is entered, the bar is colored green and can be executed. Invalid queries are colored red. The UI will automatically update to indicate which fields and values are selected in the query.
Apply the query¶
After entering a query, run it by clicking the Apply button. To clear the query, use the Reset button.
Continuing with the example, executing the query displays information on the matching documents.
To clear a query, use the Reset button.
The query is executed on the full collection. If the result set is larger than the sampleSize threshold (100 documents), then a random subset of sampleSize documents is chosen from the result set and displayed in the UI.
Documents can be examined in the document viewing pane. This can be expanded by clicking on the Document Viewer icon on the right-hand side of the page.
By default, the pane displays all of the documents sampled by Compass. If a query is specified in the query bar, only documents that match the query are shown.
Frequently Asked Questions¶
What is the performance impact of running this tool?¶
Testing has shown that Compass has minimal impact in prototype deployments, though additional performance testing and monitoring is in progress.
For best results, use MongoDB 3.2, which includes the $sample operator for efficient sampling on a collection. On older versions of MongoDB, Compass falls back on a less efficient sampling method.
It is recommended to only execute queries that are appropriately indexed in the database to avoid scanning the entire collection.
What is sampling and why is it used?¶
Sampling in Compass is the procedure of selecting a subset of data from a particular collection and analyzing the documents within the sample set.
Sampling is a common technique in statistical analysis because analyzing a subset of the data gives similar results to analyzing all of it. In addition, sampling allows results to be generated quickly rather than performing a computationally-expensive collection scan.
How does sampling work?¶
Compass employs two distinct sampling mechanisms.
In MongoDB 3.2, collections are sampled with the $sample operator via the Aggregation Pipeline. This provides efficient random sampling without replacement over the entire collection, or over the subset of documents specified by a query.
In MongoDB 3.0 and 2.6, collections are sampled via a backwards-compatible algorithm executed entirely within Compass. It takes place in three stages:
- Compass opens a cursor on the desired collection, limited to at most 10000 documents sorted in descending order of the _id field.
- sampleSize documents are randomly selected from the stream. To do this efficiently, Compass employs reservoir sampling.
- Compass performs a query to select the chosen documents directly via _id .
sampleSize is set to 100 documents.
Note that the choice of sampling method is done transparently in the background, with no changes required by the user.
Won’t sampling miss documents?¶
Sampling is chosen for its efficiency: the amount of time required to perform a sample is minimal, on the order of a few seconds. Increasing the sample confidence will demand more processing power and time. Furthermore, sophisticated outlier detection requires an inspection of every document in a MongoDB deployment, which would be unfeasible for large data sets. The MongoDB team is in the process of conducting user tests on large data sets to find a reasonable balance.
For a list of known issues, please see the MongoDB Compass JIRA project.
Any questions, concerns or feedback on MongoDB Compass is appreciated. To report a bug, submit a ticket to the MongoDB Commercial Support JIRA. To submit a feature request, use the Compass JIRA.
Was this page helpful?
Thank you for your feedback!
We’re sorry! You can Report a Problem to help us improve this page.
© MongoDB, Inc 2008-2016. MongoDB, Mongo, and the leaf logo are registered trademarks of MongoDB, Inc.
GUI MongoDB Compass
С версии MongoDB 3.2 в качестве графической оболочки поставляется «MongoDB Compass». Это удобный Клиент, разработанный MongoDB Inc для администрирования и просмотра данных. Доступен для ОС Linux, Mac и Windows.
- Просматривать, добавлять и удалять базы данных и коллекции
- Использовать все функции CRUD для работы c документами
- Выполнять и оптимизировать запросы с помощью графического интерфейса
- Визуализировать геопространственые данные и использовать их в запросах
- Работать с индексами
- Расширять возможности Compass, используя дополнительные плагины или даже, создавать собственные
- Построение соединяющих связей с помощью интуитивно-понятного графического интерфейса
Вы можете установить Compass с официального сайта www.mongodb.com. Инструкции по установке на различные платформы можно найти там же, пройдя по данной ссылке
Подключение к MongoDB
После загрузки Клиента, Вы можете подключиться к БД Вашего аккаунта, используя данные доступа по SSH. Для этого необходимо зайти в панель управления и во вкладке «FTP/Файлы → Файловый менеджер» скачать закрытый ключ id_rsa из директории .ssh, которая находится в корне домашней папки.
Файл закрытого ключа необходимо хранить в надежном месте и не передавать никому, потому что с его помощью можно без пароля получить доступ к Вашему аккаунту на хостинге Hostland
После этого нужно выбрать опцию Use Identity File в поле SSH Tunnel и заполнить следующие поля:
- SSH Hostname: техническое имя Вашего сайта
- SSH Tunnel Port: 1024 по умолчанию
- SSH Username: номер вашего аккаунта
- SSH Identity File: выберите скачанный файл с закрытым ключом
После заполнения всех данных, нажмите Connect для подключения к БД Mongo
После успешного подключения, Compass отобразит все базы данных и коллекции, доступные для работы, их размер и количество индексов в каждой из них. Здесь Вы можете создать новую базу данных или добавить коллекции к уже существующим, а также проверить скорость исполнения во вкладке PERFORMANCE
Выбрав коллекцию, Вы увидите количество созданных документов, их содержимое и размер. Можно просматривать их в виде списка или таблицы. Также, появится возможность добавления, правки и удаления текущих документов.
При переходе на вкладку Schema , Compass самостоятельно сделает выборку из текущего документа. Выборка включает в себя сведения о содержимом полей (fields), такие как, типы данных, минимальное и максимальное значения дат и целых чисел, дату и время создания и много дополнительной информации.
Можно сделать фильтр данных, просто выбрав необходимые Вам при помощи мыши и нажав ANALYZE. Compass создаст за Вас запрос к БД и выведет результат.
Подробную информацию по работе с GUI Compass можно найти на официальном сайте MongoDB, который также предлагает пройти бесплатное обучение.