How to install mongodb on ubuntu
How to install mongodb on ubuntu
Установка MongoDB в Ubuntu
Реляционные базы данных обычно используются для данных, которым важна сохранность и максимальная надёжность. Объектно-ориентированные базы данных более быстрые, но менее надёжные и часто используются для хранения различных событий и статистических данных. В этой инструкции я расскажу, как выполняется установка MongoDB Ubuntu 20.04.
Установка MongoDB
1. Установка из репозитория дистрибутива
В современных дистрибутивах утилита добавлена в официальный репозиторий современных версий Ubuntu. Для её установки достаточно выполнить:
sudo apt install mongodb-server
Затем можно посмотреть состояние службы:
sudo systemctl status mongod
И добавить её в автозагрузку, если это необходимо:
sudo systemctl enable mongod
Работать с базой данных можно через клиент командной строки Mongo. Например, давайте посмотрим версию базы данных:
Если вы собираетесь удалить MongoDB, то обратите внимание, что эта база данных может уже использоваться каким-либо приложением, поэтому сначала убедитесь, что, удалив её, вы ничего не сломаете.
1. Установка из репозитория разработчиков
Если вы хотите получить самую свежую версию программы, то необходимо устанавливать её из репозитория разработчиков MongoDB. Прежде чем устанавливать эту версию, надо удалить версию из официальных репозиториев, если она была установлена:
sudo apt purge mongodb*
Далее нужно интегрировать публичный ключ, чтобы система приняла пакет, для этого наберите в терминале:
С помощью следующей команды создаём список файлов пакета:
echo «deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.2 multiverse» | sudo tee /etc/apt/sources.list.d/mongodb-org-4.2.list
Обновим базу данных локальных пакетов:
sudo apt update
И можно переходить к установке:
Далее надо запустить сервис mongod и добавить его в автозагрузку:
sudo systemctl start mongod
sudo systemctl enable mongod
sudo systemctl status mongod
Далее смотрим версию:
Настройка MongoDB
По умолчанию база данных не защищена паролем и подключится к ней может кто угодно. Чтобы этого избежать, надо защитить базу данных. Для этого нужно создать базу данных и пользователя для неё, который сможет управлять всеми базами данных. Войдите в интерфейс управления Mongo:
Переключитесь в базу данных admin и создайте нового пользователя:
Здесь мы задаём имя пользователя Admin и разрешаем ему доступ ко всем базам данных. После нажатия Enter программа запросит пароль для нового пользователя. Введите пароль и всё будет готово.
Далее откройте конфигурационный файл /etc/mongod.conf и добавьте туда такие строчки:
sudo vi /etc/mongod.conf
security:
authorization: enabled
Затем перезапустите MongoDB:
sudo systemctl restart mongod
После этого вы все ещё сможете подключится к MongoDB с помощью клиента Mongo, но чтобы выполнить какие-либо действия, вам понадобится авторизация. Например, вы не сможете посмотреть список баз данных, создать пользователя или получить данные из базы. Например, команда show databases вернёт пустой результат:
Для подключения с авторизацией используйте команду:
Удаление MongoDB
Чтобы удалить MongoDB с компьютера, наберите:
sudo apt purge mongodb-org*
Или если вы устанавливали программу из официальных репозиториев, используйте:
sudo apt purge mongodb*
Теперь вы знаете, как установить MongoDB Ubuntu 18.04 на ваш компьютер, а также как проверить, какая версия у вас установлена, и работает ли вообще эта база данных.
Install MongoDB Community Edition on Ubuntu
is a hosted MongoDB service option in the cloud which requires no installation overhead and offers a free tier to get started.
Overview
Use this tutorial to install MongoDB 4.4 Community Edition on LTS (long-term support) releases of Ubuntu Linux using the apt package manager.
MongoDB Version
Considerations
Platform Support
MongoDB 4.4 Community Edition supports the following 64-bit Ubuntu LTS (long-term support) releases on x86_64 architecture:
MongoDB only supports the 64-bit versions of these platforms.
MongoDB 4.4 Community Edition on Ubuntu also supports the ARM64 and s390x architectures on select platforms.
See Platform Support Notes for more information.
Production Notes
Before deploying MongoDB in a production environment, consider the Production Notes document which offers performance considerations and configuration recommendations for production MongoDB deployments.
Official MongoDB Packages
To install MongoDB Community on your Ubuntu system, these instructions will use the official mongodb-org package, which is maintained and supported by MongoDB Inc. The official mongodb-org package always contains the latest version of MongoDB, and is available from its own dedicated repo.
The mongodb package provided by Ubuntu is not maintained by MongoDB Inc. and conflicts with the official mongodb-org package. If you have already installed the mongodb package on your Ubuntu system, you must first uninstall the mongodb package before proceeding with these instructions.
See MongoDB Community Edition Packages for the complete list of official packages.
Install MongoDB Community Edition
Follow these steps to install MongoDB Community Edition using the apt package manager.
Import the public key used by the package management system.
From a terminal, issue the following command to import the MongoDB public GPG Key from https://www.mongodb.org/static/pgp/server-4.4.asc
However, if you receive an error indicating that gnupg is not installed, you can:
Install gnupg and its required libraries using the following command:
Once installed, retry importing the key:
Create a list file for MongoDB.
Create the list file /etc/apt/sources.list.d/mongodb-org-4.4.list for your version of Ubuntu.
Reload local package database.
Issue the following command to reload the local package database:
Install the MongoDB packages.
You can install either the latest stable version of MongoDB or a specific version of MongoDB.
Optional. Although you can specify any available version of MongoDB, apt-get will upgrade the packages when a newer version becomes available. To prevent unintended upgrades, you can pin the package at the currently installed version:
For help with troubleshooting errors encountered while installing MongoDB on Ubuntu, see our troubleshooting guide.
Run MongoDB Community Edition
If you installed via the package manager, the data directory /var/lib/mongodb and the log directory /var/log/mongodb are created during the installation.
By default, MongoDB runs using the mongodb user account. If you change the user that runs the MongoDB process, you must also modify the permission to the data and log directories to give this user access to these directories.
Configuration File The official MongoDB package includes a configuration file ( /etc/mongod.conf ). These settings (such as the data directory and log directory specifications) take effect upon startup. That is, if you change the configuration file while the MongoDB instance is running, you must restart the instance for the changes to take effect.
Procedure
Init System
To run and manage your mongod process, you will be using your operating system’s built-in init system. Recent versions of Linux tend to use systemd (which uses the systemctl command), while older versions of Linux tend to use System V init (which uses the service command).
If you are unsure which init system your platform uses, run the following command:
Then select the appropriate tab below based on the result:
Uninstall MongoDB Community Edition
To completely remove MongoDB from a system, you must remove the MongoDB applications themselves, the configuration files, and any directories containing data and logs. The following section guides you through the necessary steps.
This process will completely remove MongoDB, its configuration, and all databases. This process is not reversible, so ensure that all of your configuration and data is backed up before proceeding.
Install MongoDB Community Edition on Ubuntu
is a hosted MongoDB service option in the cloud which requires no installation overhead and offers a free tier to get started.
Overview
Use this tutorial to install MongoDB 6.0 Community Edition on LTS (long-term support) releases of Ubuntu Linux using the apt package manager.
MongoDB Version
Considerations
Platform Support
MongoDB 6.0 Community Edition supports the following 64-bit Ubuntu LTS (long-term support) releases on x86_64 architecture:
MongoDB only supports the 64-bit versions of these platforms.
MongoDB 6.0 Community Edition on Ubuntu also supports the ARM64 architecture on select platforms.
See Platform Support for more information.
Production Notes
Before deploying MongoDB in a production environment, consider the Production Notes document which offers performance considerations and configuration recommendations for production MongoDB deployments.
Official MongoDB Packages
To install MongoDB Community on your Ubuntu system, these instructions will use the official mongodb-org package, which is maintained and supported by MongoDB Inc. The official mongodb-org package always contains the latest version of MongoDB, and is available from its own dedicated repo.
The mongodb package provided by Ubuntu is not maintained by MongoDB Inc. and conflicts with the official mongodb-org package. If you have already installed the mongodb package on your Ubuntu system, you must first uninstall the mongodb package before proceeding with these instructions.
See MongoDB Community Edition Packages for the complete list of official packages.
Install MongoDB Community Edition
Follow these steps to install MongoDB Community Edition using the apt package manager.
Import the public key used by the package management system.
From a terminal, issue the following command to import the MongoDB public GPG Key from https://www.mongodb.org/static/pgp/server-6.0.asc
However, if you receive an error indicating that gnupg is not installed, you can:
Install gnupg and its required libraries using the following command:
Once installed, retry importing the key:
Create a list file for MongoDB.
Create the list file /etc/apt/sources.list.d/mongodb-org-6.0.list for your version of Ubuntu.
Reload local package database.
Issue the following command to reload the local package database:
Install the MongoDB packages.
You can install either the latest stable version of MongoDB or a specific version of MongoDB.
Optional. Although you can specify any available version of MongoDB, apt-get will upgrade the packages when a newer version becomes available. To prevent unintended upgrades, you can pin the package at the currently installed version:
For help with troubleshooting errors encountered while installing MongoDB on Ubuntu, see our troubleshooting guide.
Run MongoDB Community Edition
If you installed via the package manager, the data directory /var/lib/mongodb and the log directory /var/log/mongodb are created during the installation.
By default, MongoDB runs using the mongodb user account. If you change the user that runs the MongoDB process, you must also modify the permission to the data and log directories to give this user access to these directories.
Configuration File The official MongoDB package includes a configuration file ( /etc/mongod.conf ). These settings (such as the data directory and log directory specifications) take effect upon startup. That is, if you change the configuration file while the MongoDB instance is running, you must restart the instance for the changes to take effect.
Procedure
Init System
To run and manage your mongod process, you will be using your operating system’s built-in init system. Recent versions of Linux tend to use systemd (which uses the systemctl command), while older versions of Linux tend to use System V init (which uses the service command).
If you are unsure which init system your platform uses, run the following command:
Then select the appropriate tab below based on the result:
Uninstall MongoDB Community Edition
To completely remove MongoDB from a system, you must remove the MongoDB applications themselves, the configuration files, and any directories containing data and logs. The following section guides you through the necessary steps.
This process will completely remove MongoDB, its configuration, and all databases. This process is not reversible, so ensure that all of your configuration and data is backed up before proceeding.
How To Install MongoDB on Ubuntu 20.04
An earlier version of this tutorial was written by Melissa Anderson.
Introduction
MongoDB is a document database used in many modern web applications. It is classified as a NoSQL database because it does not rely on a traditional table-based relational database structure.
Instead, it uses JSON-like documents with dynamic schemas, meaning that, unlike relational databases, MongoDB does not require a predefined schema before you add data to a database. You can alter the schema at any time and as often as is necessary without having to set up a new database with an updated schema.
In this tutorial you’ll install MongoDB on an Ubuntu 20.04 server, test it, and learn how to manage it as a systemd service.
Prerequisites
To follow this tutorial, you will need:
Step 1 — Installing MongoDB
This command will return OK if the key was added successfully:
If you’d like to double check that the key was added correctly, you can do so with the following command:
This will return the MongoDB key somewhere in the output:
At this point, your APT installation still doesn’t know where to find the mongodb-org package you need to install the latest version of MongoDB.
There are two places on your server where APT looks for online sources of packages to download and install: the sources.list file and the sources.list.d directory. sources.list is a file that lists active sources of APT data, with one source per line and the most preferred sources listed first. The sources.list.d directory allows you to add such sources.list entries as separate files.
This single line tells APT everything it needs to know about what the source is and where to find it:
After running this command, update your server’s local package index so APT knows where to find the mongodb-org package:
Following that, you can install MongoDB:
When prompted, press Y and then ENTER to confirm that you want to install the package.
When the command finishes, MongoDB will be installed on your system. However it isn’t yet ready to use. Next, you’ll start MongoDB and confirm that it’s working correctly.
Step 2 — Starting the MongoDB Service and Testing the Database
Run the following systemctl command to start the MongoDB service:
This command will return output like the following, indicating that the service is up and running:
After confirming that the service is running as expected, enable the MongoDB service to start up at boot:
You can further verify that the database is operational by connecting to the database server and executing a diagnostic command. The following command will connect to the database and output its current version, server address, and port. It will also return the result of MongoDB’s internal connectionStatus command:
connectionStatus will check and return the status of the database connection. A value of 1 for the ok field in the response indicates that the server is working as expected:
Step 3 — Managing the MongoDB Service
As mentioned previously, the installation process described in Step 1 configures MongoDB to run as a systemd service. This means that you can manage it using standard systemctl commands as you would with other Ubuntu system services.
As mentioned previously, the systemctl status command checks the status of the MongoDB service:
You can stop the service anytime by typing:
To start the service when it’s stopped, run:
You can also restart the server when it’s already running:
In Step 2, you enabled MongoDB to start automatically with the server. If you ever wish to disable this automatic startup, type:
Then to re-enable it to start up at boot, run the enable command again:
For more information on how to manage systemd services, check out Systemd Essentials: Working with Services, Units, and the Journal.
Conclusion
In this tutorial, you added the official MongoDB repository to your APT instance, and installed the latest version of MongoDB. You then tested Mongo’s functionality and practiced some systemctl commands.
As an immediate next step, we strongly recommend that you harden your MongoDB installation’s security by following our guide on How To Secure MongoDB on Ubuntu 20.04. Once it’s secured, you could then configure MongoDB to accept remote connections.
You can find more tutorials on how to configure and use MongoDB in these DigitalOcean community articles. We also encourage you to check out the official MongoDB documentation, as it’s a great resource on the possibilities that MongoDB provides.
Want to learn more? Join the DigitalOcean Community!
Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.
Install MongoDB Community Edition on Ubuntu
is a hosted MongoDB service option in the cloud which requires no installation overhead and offers a free tier to get started.
Overview
Use this tutorial to install MongoDB 6.0 Community Edition on LTS (long-term support) releases of Ubuntu Linux using the apt package manager.
MongoDB Version
Considerations
Platform Support
MongoDB 6.0 Community Edition supports the following 64-bit Ubuntu LTS (long-term support) releases on x86_64 architecture:
MongoDB only supports the 64-bit versions of these platforms.
MongoDB 6.0 Community Edition on Ubuntu also supports the ARM64 architecture on select platforms.
See Platform Support for more information.
Production Notes
Before deploying MongoDB in a production environment, consider the Production Notes document which offers performance considerations and configuration recommendations for production MongoDB deployments.
Official MongoDB Packages
To install MongoDB Community on your Ubuntu system, these instructions will use the official mongodb-org package, which is maintained and supported by MongoDB Inc. The official mongodb-org package always contains the latest version of MongoDB, and is available from its own dedicated repo.
The mongodb package provided by Ubuntu is not maintained by MongoDB Inc. and conflicts with the official mongodb-org package. If you have already installed the mongodb package on your Ubuntu system, you must first uninstall the mongodb package before proceeding with these instructions.
See MongoDB Community Edition Packages for the complete list of official packages.
Install MongoDB Community Edition
Follow these steps to install MongoDB Community Edition using the apt package manager.
Import the public key used by the package management system.
From a terminal, issue the following command to import the MongoDB public GPG Key from https://www.mongodb.org/static/pgp/server-6.0.asc
However, if you receive an error indicating that gnupg is not installed, you can:
Install gnupg and its required libraries using the following command:
Once installed, retry importing the key:
Create a list file for MongoDB.
Create the list file /etc/apt/sources.list.d/mongodb-org-6.0.list for your version of Ubuntu.
Reload local package database.
Issue the following command to reload the local package database:
Install the MongoDB packages.
You can install either the latest stable version of MongoDB or a specific version of MongoDB.
Optional. Although you can specify any available version of MongoDB, apt-get will upgrade the packages when a newer version becomes available. To prevent unintended upgrades, you can pin the package at the currently installed version:
For help with troubleshooting errors encountered while installing MongoDB on Ubuntu, see our troubleshooting guide.
Run MongoDB Community Edition
If you installed via the package manager, the data directory /var/lib/mongodb and the log directory /var/log/mongodb are created during the installation.
By default, MongoDB runs using the mongodb user account. If you change the user that runs the MongoDB process, you must also modify the permission to the data and log directories to give this user access to these directories.
Configuration File The official MongoDB package includes a configuration file ( /etc/mongod.conf ). These settings (such as the data directory and log directory specifications) take effect upon startup. That is, if you change the configuration file while the MongoDB instance is running, you must restart the instance for the changes to take effect.
Procedure
Init System
To run and manage your mongod process, you will be using your operating system’s built-in init system. Recent versions of Linux tend to use systemd (which uses the systemctl command), while older versions of Linux tend to use System V init (which uses the service command).
If you are unsure which init system your platform uses, run the following command:
Then select the appropriate tab below based on the result:
Uninstall MongoDB Community Edition
To completely remove MongoDB from a system, you must remove the MongoDB applications themselves, the configuration files, and any directories containing data and logs. The following section guides you through the necessary steps.
This process will completely remove MongoDB, its configuration, and all databases. This process is not reversible, so ensure that all of your configuration and data is backed up before proceeding.