Mongodb ��� ���������� linux

Install MongoDBВ¶

Author: MongoDB Documentation Team

This guide describes how to install MongoDB locally. If you would like to use MongoDB in the Cloud using Atlas , our managed database product, see Get Started with Atlas.

Time required: 10 minutes

What You’ll Need¶

MongoDB supports a variety of 64-bit platforms. Refer to the Supported Platforms table to verify that MongoDB is supported on the platform to which you wish to install it.

ProcedureВ¶

Install MongoDBВ¶

Download the binaries from the MongoDB Download Center.

Open Windows Explorer/File Explorer.

Change the directory path to where you downloaded the MongoDB .msi file. By default, this is %HOMEPATH%\Downloads .

Double-click the .msi file.

The Windows Installer guides you through the installation process.

If you choose the Custom installation option, you may specify an installation directory.

MongoDB does not have any other system dependencies. You can install and run MongoDB from any folder you choose.

This tutorial assumes that you installed MongoDB in C:\Program Files\MongoDB\Server\4.2\ .

MongoDB only supports macOS versions 10.11 and later on Intel x86-64.

Download the binary files for the desired release of MongoDB.В¶

Download the binaries from the MongoDB Download Center.

Extract the files from the downloaded archive.В¶

For example, from a system shell, you can extract through the tar command:

Copy the extracted archive to the target directory.В¶

Copy the extracted folder to the location from which MongoDB will run.

Ensure the location of the binaries is in the PATH variable.В¶

The MongoDB binaries are in the bin/ directory of the archive. To ensure that the binaries are in your PATH , you can modify your PATH .

For example, you can add the following line to your shell’s rc file (e.g.

Replace with the path to the extracted MongoDB archive.

These instructions are for installing MongoDB directly from an archive file. If you would rather use your linux distribution’s package manager, refer to the installation instructions for your distribution in the MongoDB Manual.

Download the binary files for the desired release of MongoDB.В¶

Download the binaries from the MongoDB Download Center.

Extract the files from the downloaded archive.В¶

Extract the archive by double-clicking on the tar file or using the tar command from the command line, as in the following:

Copy the extracted archive to the target directory.В¶

Copy the extracted folder to the location from which MongoDB will run.

Ensure the location of the binaries is in the PATH variable.В¶

The MongoDB binaries are in the bin/ directory of the archive. To ensure that the binaries are in your PATH , you can modify your PATH .

For example, you can add the following line to your shell’s rc file (e.g.

Replace with the path to the extracted MongoDB archive.

Run MongoDBВ¶

Do not make mongod.exe visible on public networks without running in “Secure Mode” with the auth setting. MongoDB is designed to be run in trusted environments, and the database does not enable “Secure Mode” by default.

Читайте также:  Intel rapid storage technology driver linux

Set up the MongoDB environment.В¶

MongoDB requires a data directory to store all data. MongoDB’s default data directory path is the absolute path \data\db on the drive from which you start MongoDB. Create this folder by running the following command in a Command Prompt :

You can specify an alternate path for data files using the —dbpath option to mongod.exe , for example:

If your path includes spaces, enclose the entire path in double quotes, for example:

You may also specify the dbpath in a configuration file.

Start MongoDB.В¶

To start MongoDB, run mongod.exe . For example, from the Command Prompt :

This starts the main MongoDB database process. The waiting for connections message in the console output indicates that the mongod.exe process is running successfully.

Depending on the security level of your system, Windows may pop up a Security Alert dialog box about blocking “some features” of C:\Program Files\MongoDB\Server\4.0\bin\mongod.exe from communicating on networks. All users should select Private Networks, such as my home or work network and click Allow access . For additional information on security and MongoDB, please see the Security Documentation.

Verify that MongoDB has started successfullyВ¶

Verify that MongoDB has started successfully by checking the process output for the following line:

The output should be visible in the terminal or shell window.

You may see non-critical warnings in the process output. As long as you see the log line shown above, you can safely ignore these warnings during your initial evaluation of MongoDB.

Connect to MongoDB.В¶

To connect to MongoDB through the

bin.mongo.exe shell, open another Command Prompt .

Create the data directoryВ¶

Before you start MongoDB for the first time, create the directory to which the mongod process will write data. By default, the mongod process uses the /data/db directory. If you create a directory other than this one, you must specify that directory in the dbpath option when starting the mongod process later in this procedure.

The following example command creates the default /data/db directory:

Set permissions for the data directoryВ¶

Before running mongod for the first time, ensure that the user account running mongod has read and write permissions for the directory.

Run MongoDBВ¶

To run MongoDB, run the mongod process at the system prompt. If necessary, specify the path of the mongod or the data directory. See the following examples.

Run without specifying pathsВ¶

If your system PATH variable includes the location of the mongod binary and if you use the default data directory (i.e., /data/db ), simply enter mongod at the system prompt:

Specify the path of the mongod В¶

If your PATH does not include the location of the mongod binary, enter the full path to the mongod binary at the system prompt:

Источник

Установка MongoDB в Ubuntu

MongoDB — популярная реализация нереляционной базы данных. Если в двух словах, то базы данных бывают нескольких типов. Базы реляционного типа — самые популярные, хранят данные в записях таблицы, которая состоит из столбцов и строк. MongoDB принадлежит к объектно-ориентированному типу. Главное отличие этого типа в том, что работа и хранение данных осуществляется с помощью объектов, точно так же, как это делается в популярных объективно-ориентированных языках программирования (C++, Java).

Реляционные базы данных обычно используются для данных, которым важна сохранность и максимальная надёжность. Объектно-ориентированные базы данных более быстрые, но менее надёжные и часто используются для хранения различных событий и статистических данных. В этой инструкции я расскажу, как выполняется установка MongoDB Ubuntu 20.04.

Установка MongoDB

1. Установка из репозитория дистрибутива

В современных дистрибутивах утилита добавлена в официальный репозиторий современных версий Ubuntu. Для её установки достаточно выполнить:

sudo apt install mongodb-server

Затем можно посмотреть состояние службы:

sudo systemctl status mongod

И добавить её в автозагрузку, если это необходимо:

sudo systemctl enable mongod

Работать с базой данных можно через клиент командной строки Mongo. Например, давайте посмотрим версию базы данных:

Читайте также:  Разбить диск windows 2012

Если вы собираетесь удалить MongoDB, то обратите внимание, что эта база данных может уже использоваться каким-либо приложением, поэтому сначала убедитесь, что, удалив её, вы ничего не сломаете.

1. Установка из репозитория разработчиков

Если вы хотите получить самую свежую версию программы, то необходимо устанавливать её из репозитория разработчиков MongoDB. Прежде чем устанавливать эту версию, надо удалить версию из официальных репозиториев, если она была установлена:

sudo apt purge mongodb*

Далее нужно интегрировать публичный ключ, чтобы система приняла пакет, для этого наберите в терминале:

wget -qO — https://www.mongodb.org/static/pgp/server-4.2.asc | sudo apt-key add —

С помощью следующей команды создаём список файлов пакета:

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

И можно переходить к установке:

sudo apt install -y mongodb-org

Далее надо запустить сервис mongod и добавить его в автозагрузку:

sudo systemctl start mongod
sudo systemctl enable mongod
sudo systemctl status mongod

Далее смотрим версию:

Если что-то не работает, логи сервиса можно посмотреть в папке /var/log/mongodb, файлы баз данных — /var/lib/mongodb.

Настройка 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 вернёт пустой результат:

Для подключения с авторизацией используйте команду:

$ mongo —authenticationDatabase имя_базы_данных -u имя_пользователя -p

mongo —authenticationDatabase «admin» -u «Admin» -p

Удаление MongoDB

Чтобы удалить MongoDB с компьютера, наберите:

sudo apt purge mongodb-org*

Или если вы устанавливали программу из официальных репозиториев, используйте:

sudo apt purge mongodb*

Теперь вы знаете, как установить MongoDB Ubuntu 18.04 на ваш компьютер, а также как проверить, какая версия у вас установлена, и работает ли вообще эта база данных.

Источник

How to Install MongoDB on Ubuntu

Last updated March 4, 2019 By Sergiu 10 Comments

This tutorial presents two ways to install MongoDB on Ubuntu and Ubuntu-based Linux distributions.

MongoDB is an increasingly popular free and open-source NoSQL database that stores data in collections of JSON-like, flexible documents, in contrast to the usual table approach you’ll find in SQL databases.

You are most likely to find MongoDB used in modern web applications. Its document model makes it very intuitive to access and handle with various programming languages.

In this article, I’ll cover two ways you can install MongoDB on your Ubuntu system.

Installing MongoDB on Ubuntu based Distributions

  1. Install MongoDB using Ubuntu’s repository. Easy but not the latest version of MongoDB
  2. Install MongoDB using its official repository. Slightly complicated but you get the latest version of MongoDB.

The first installation method is easier, but I recommend the second method if you plan on using the latest release with official support.

Some people might prefer using snap packages. There are snaps available in the Ubuntu Software Center, but I wouldn’t recommend using them; they’re outdated at the moment and I won’t be covering that.

Method 1. Install MongoDB from Ubuntu Repository

This is the easy way to install MongoDB on your system, you only need to type in a simple command.

Installing MongoDB

First, make sure your packages are up-to-date. Open up a terminal and type:

Go ahead and install MongoDB with:

That’s it! MongoDB is now installed on your machine.

Читайте также:  Linux mint терминальный сервер

The MongoDB service should automatically be started on install, but to check the status type

You can see that the service is active.

Running MongoDB

MongoDB is currently a systemd service, so we’ll use systemctl to check and modify it’s state, using the following commands:

You can also change if MongoDB automatically starts when the system starts up (default: enabled):

To start working with (creating and editing) databases, type:

This will start up the mongo shell. Please check out the manual for detailed information on the available queries and options.

Note: Depending on how you plan to use MongoDB, you might need to adjust your Firewall. That’s unfortunately more involved than what I can cover here and depends on your configuration.

Uninstall MongoDB

If you installed MongoDB from the Ubuntu Repository and want to uninstall it (maybe to install using the officially supported way), type:

This should completely get rid of your MongoDB install. Make sure to backup any collections or documents you might want to keep since they will be wiped out!

Method 2. Install MongoDB Community Edition on Ubuntu

This is the way the recommended way to install MongoDB, using the package manager. You’ll have to type a few more commands and it might be intimidating if you are newer to the Linux world.

But there’s nothing to be afraid of! We’ll go through the installation process step by step.

Installing MongoDB

The package maintained by MongoDB Inc. is called mongodb-org, not mongodb (this is the name of the package in the Ubuntu Repository). Make sure mongodb is not installed on your system before applying this steps. The packages will conflict. Let’s get to it!

First, we’ll have to import the public key:

Now, you need to add a new repository in your sources list so that you can install MongoDB Community Edition and also get automatic updates:

To be able to install mongodb -org, we’ll have to update our package database so that your system is aware of the new packages available:

Now you can ether install the latest stable version of MongoDB:

or a specific version (change the version number after equal sign)

If you choose to install a specific version, make sure you change the version number everywhere. If you only change it in the mongodb-org=4.0.6 part, the latest version will be installed.

By default, when updating using the package manager (apt-get), MongoDB will be updated to the newest updated version. To stop that from happening (and freezing to the installed version), use:

You have now successfully installed MongoDB!

Configuring MongoDB

By default, the package manager will create /var/lib/ mongodb and /var/log/ mongodb and MongoDB will run using the mongodb user account.

I won’t go into changing these default settings since that is beyond the scope of this guide. You can check out the manual for detailed information.

The settings in /etc/mongod.conf are applied when starting/restarting the mongodb service instance.

Running MongoDB

To start the mongodb daemonmongod, type:

Now you should verify that the mongod process started successfully. This information is stored (by default) at /var/log/mongodb/mongod.log. Let’s check the contents of that file:

As long as you get this: [initandlisten] waiting for connections on port 27017 somewhere in there, the process is running properly.

Note: 27017 is the default port of mongod.

To stop/restart mongod enter:

Now, you can use MongoDB by opening the mongo shell:

Uninstall MongoDB

Run the following commands

To remove the databases and log files (make sure to backup what you want to keep!):

Wrapping Up

MongoDB is a great NoSQL database, easy to integrate in to modern projects. I hope this tutorial helped you to set it up on your Ubuntu machine! Let us know how you plan on using MongoDB in the comments below.

Like what you read? Please share it with others.

Источник

Оцените статью