Как установить монго дб на мак ос

Обновлено: 03.07.2024

MongoDB Atlas 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 5.0 Community Edition on macOS using the third-party Homebrew package manager.

Starting with MongoDB 4.4.1, installing MongoDB via Homebrew also installs the MongoDB Database Tools. See Using the MongoDB Database Tools for more information.

MongoDB Version¶

This tutorial installs MongoDB 5.0 Community Edition. To install a different version of MongoDB Community , use the version drop-down menu in the upper-left corner of this page to select the documentation for that version.

Considerations¶

Platform Support¶

  • MongoDB 5.0 Community Edition removes support for macOS 10.13

MongoDB 5.0 Community Edition supports macOS 10.14 or later.

See Supported Platforms 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.

Install MongoDB Community Edition¶

Prerequisites¶

Ensure your system meets each of the following prerequisites. You only need to perform each prerequisite step once on your system. If you have already performed the prerequisite steps as part of an earlier MongoDB installation using Homebrew, you can skip to the installation procedure.

Install Xcode Command-Line Tools¶

Install the Xcode command-line tools by running the following command in your macOS Terminal:

Install Homebrew¶

macOS does not include the Homebrew brew package by default.

Installing MongoDB 5.0 Community Edition¶

Tap the MongoDB Homebrew Tap to download the official Homebrew formula for MongoDB and the Database Tools, by running the following command in your macOS Terminal:

If you have already done this for a previous installation of MongoDB, you can skip this step.

To install MongoDB, run the following command in your macOS Terminal application:

Alternatively, you can specify a previous version of MongoDB if desired. You can also maintain multiple versions of MongoDB side by side in this manner.

If you have previously installed an older version of the formula, you may encounter a ChecksumMismatchError. To resolve, see Troubleshooting ChecksumMismatchError.

The installation includes the following binaries:

  • The mongod server
  • The mongos sharded cluster query router
  • The MongoDB Shell, mongosh

Starting with MongoDB 4.4.1, the installation also includes the MongoDB Database Tools. See Using the MongoDB Database Tools for more information.

Run MongoDB Community Edition¶

Follow these steps to run MongoDB Community Edition. These instructions assume that you are using the default settings.

You can run MongoDB as a macOS service using brew , or you can run MongoDB manually as a background process. It is recommended to run MongoDB as a macOS service, as doing so sets the correct system ulimit values automatically (see ulimit settings for more information).

To run MongoDB (i.e. the mongod process) as a macOS service, run:

To stop a mongod running as a macOS service, use the following command as needed:

To run MongoDB (i.e. the mongod process) manually as a background process, run:

For macOS running Intel processors:

To stop a mongod running as a background process, connect to the mongod using mongosh, and issue the shutdown command as needed.

Both methods use the mongod.conf file created during the install. You can add your own MongoDB configuration options to this file as well.

macOS may prevent mongod from running after installation. If you receive a security error when starting mongod indicating that the developer could not be identified or verified, do the following to grant mongod access to run:

  • Open System Preferences
  • Select the Security and Privacy pane.
  • Under the General tab, click the button to the right of the message about mongod , labelled either Open Anyway or Allow Anyway depending on your version of macOS.

To verify that MongoDB is running, perform one of the following:

If you started MongoDB as a macOS service:

You should see the service mongodb-community listed as started .

If you started MongoDB manually as a background process:

You should see your mongod process in the output.

You can also view the log file to see the current status of your mongod process: /usr/local/var/log/mongodb/mongo.log .

Connect and Use MongoDB¶

To begin using MongoDB, connect mongosh to the running instance. From a new terminal, issue the following:

macOS may prevent mongosh from running after installation. If you receive a security error when starting mongosh indicating that the developer could not be identified or verified, do the following to grant mongosh access to run:

  • Open System Preferences
  • Select the Security and Privacy pane.
  • Under the General tab, click the button to the right of the message about mongosh , labelled either Open Anyway or Allow Anyway depending on your version of macOS.

For information on CRUD (Create,Read,Update,Delete) operations, see:

Using the MongoDB Database Tools¶

Starting in MongoDB 4.4.1, installing MongoDB via brew also installs the MongoDB Database Tools.

The MongoDB Database Tools are a collection of command-line utilities for working with a MongoDB deployment, including data backup and import/export tools like mongoimport and mongodump as well as monitoring tools like mongotop .

Once you have installed the MongoDB Server in the steps above, the Database Tools are available directly from the command line in your macOS Terminal application. For example you could run mongotop against your running MongoDB instance by invoking it in your macOS Terminal like so:

It should start up, connect to your running mongod , and start reporting usage statistics.

See the MongoDB Database Tools Documentation for usage information for each of the Database Tools.

Additional Information¶

Localhost Binding by Default¶

By default, MongoDB launches with bindIp set to 127.0.0.1 , which binds to the localhost network interface. This means that the mongod can only accept connections from clients that are running on the same machine. Remote clients will not be able to connect to the mongod , and the mongod will not be able to initialize a replica set unless this value is set to a valid network interface.

This value can be configured either:

  • in the MongoDB configuration file with bindIp , or
  • via the command-line argument --bind_ip

Before binding to a non-localhost (e.g. publicly accessible) IP address, ensure you have secured your cluster from unauthorized access. For a complete list of security recommendations, see Security Checklist. At minimum, consider enabling authentication and hardening network infrastructure.

For more information on configuring bindIp , see IP Binding.

Troubleshooting ChecksumMismatchError¶

If you have previously installed an older version of the formula, you may encounter a ChecksumMismatchError resembling the following:

Use this tutorial to install MongoDB 4.0 Community Edition on macOS using the third-party Homebrew package manager.

You can also use these instructions to install the MongoDB Database Tools. See Installing the MongoDB Database Tools for more information.

MongoDB Version¶

This tutorial installs MongoDB 4.0 Community Edition. To install a different version of MongoDB Community, use the version drop-down menu in the upper-left corner of this page to select the documentation for that version.

Considerations¶

Platform Support¶

MongoDB 4.0 Community Edition supports macOS 10.11 or later.

MongoDB 4.0 may lose data during unclean shutdowns on macOS 10.12.x, 10.13.x, and 10.14.0. This issue was fixed by Apple in macOS 10.14.1.

For details, see WT-4018.

See Supported Platforms 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.

Install MongoDB Community Edition¶

Prerequisites¶

Ensure your system meets each of the following prerequisites. You only need to perform each prerequisite step once on your system. If you have already performed the prerequisite steps as part of an earlier MongoDB installation using Homebrew, you can skip to the installation procedure .

Install Xcode Command-Line Tools¶

Homebrew requires the Xcode command-line tools from Apple’s Xcode.

Install the Xcode command-line tools by running the following command in your macOS Terminal:

Install Homebrew¶

macOS does not include the Homebrew brew package by default.

Installing MongoDB 4.0 Community Edition¶

Follow these steps to install MongoDB Community Edition using Homebrew’s brew package manager. Be sure that you have followed the installation prerequisites above before proceeding.

Tap the MongoDB Homebrew Tap to download the official Homebrew formula for MongoDB and the Database Tools, by running the following command in your macOS Terminal:

If you have already done this for a previous installation of MongoDB, you can skip this step.

To install MongoDB, run the following command in your macOS Terminal application:

Alternatively, you can specify a previous version of MongoDB if desired. You can also maintain multiple versions of MongoDB side by side in this manner.

If you have previously installed an older version of the formula, you may encounter a ChecksumMismatchError. To resolve, see Troubleshooting ChecksumMismatchError .

The installation includes the following binaries:

  • The mongod server
  • The mongos sharded cluster query router
  • The mongo shell

See Apple’s documentation for the current list of Apple hardware using the M1 processor. You can also run the following command to check where brew has installed these files and directories:

Run MongoDB Community Edition¶

Follow these steps to run MongoDB Community Edition. These instructions assume that you are using the default settings.

You can run MongoDB as a macOS service using brew , or you can run MongoDB manually as a background process. It is recommended to run MongoDB as a macOS service, as doing so sets the correct system ulimit values automatically (see ulimit settings for more information).

To run MongoDB (i.e. the mongod process) as a macOS service, issue the following:

To stop a mongod running as a macOS service, use the following command as needed:

To run MongoDB (i.e. the mongod process) manually as a background process, issue the following:

For macOS running Intel processors:

To stop a mongod running as a background process, connect to the mongod from the mongo shell, and issue the shutdown command as needed.

Both methods use the mongod.conf file created during the install. You can add your own MongoDB configuration options to this file as well.

macOS Prevents mongod From Opening

macOS may prevent mongod from running after installation. If you receive a security error when starting mongod indicating that the developer could not be identified or verified, do the following to grant mongod access to run:

  • Open System Preferences
  • Select the Security and Privacy pane.
  • Under the General tab, click the button to the right of the message about mongod , labelled either Open Anyway or Allow Anyway depending on your version of macOS.

To verify that MongoDB is running, perform one of the following:

If you started MongoDB as a macOS service:

You should see the service mongodb-community listed as started .

If you started MongoDB manually as a background process:

You should see your mongod process in the output.

You can also view the log file to see the current status of your mongod process: /usr/local/var/log/mongodb/mongo.log .

Connect and Use MongoDB¶

To begin using MongoDB, connect a mongo shell to the running instance. From a new terminal, issue the following:

macOS Prevents mongo From Opening

macOS may prevent the mongo shell from running after installation. If you receive a security error when starting the mongo shell indicating that the developer could not be identified or verified, do the following to grant the mongo shell access to run:

  • Open System Preferences
  • Select the Security and Privacy pane.
  • Under the General tab, click the button to the right of the message about the mongo shell, labelled either Open Anyway or Allow Anyway depending on your version of macOS.

For information on CRUD (Create,Read,Update,Delete) operations, see:

Installing the MongoDB Database Tools¶

The MongoDB Database Tools are a collection of command-line utilities for working with a MongoDB deployment, including data backup and import/export tools like mongoimport and mongodump as well as monitoring tools like mongotop .

Follow these steps to install the MongoDB Database Tools using Homebrew’s brew package manager.

Verify that your system meets all the installation prerequisites by running the following command in your macOS Terminal:

You should see the MongoDB brew tap listed. If you do not, or you receive an error, return to the Prerequisites section.

To install the MongoDB Database Tools, run the following command in your macOS Terminal application:

Once installed, the Database Tools are available directly from the command line in your macOS Terminal application.

For example you could run mongotop against a running MongoDB instance by invoking it in your macOS Terminal like so:

It should start up, connect to your running mongod , and start reporting usage statistics.

See the MongoDB Database Tools Documentation for usage information for each of the Database Tools.

Additional Information¶

Localhost Binding by Default¶

By default, MongoDB launches with bindIp set to 127.0.0.1 , which binds to the localhost network interface. This means that the mongod can only accept connections from clients that are running on the same machine. Remote clients will not be able to connect to the mongod , and the mongod will not be able to initialize a replica set unless this value is set to a valid network interface.

This value can be configured either:

  • in the MongoDB configuration file with bindIp , or
  • via the command-line argument --bind_ip

Before binding to a non-localhost (e.g. publicly accessible) IP address, ensure you have secured your cluster from unauthorized access. For a complete list of security recommendations, see Security Checklist . At minimum, consider enabling authentication and hardening network infrastructure .

For more information on configuring bindIp , see IP Binding .

Troubleshooting ChecksumMismatchError¶

If you have previously installed an older version of the formula, you may encounter a ChecksumMismatchError resembling the following:

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



В настоящее время MongoDB будет установлен в /usr/local/Cellar/mongodb/4.0.3 (моя версия MongoDB - 4.0.3).


b r e w An Установить Время Вне настоящее время x c r u n : e r r o r : i n v a l i d a c t i v e d e v e l o p e r p a t h ( / L i b r a r y / D e v e l o p e r / C o m m a n d L i n e T o o l s ) решение Принимать решение \ color b r e w An Установить Время Вне настоящее время x c r u n : e r r o r : i n v a l i d a c t i v e d e v e l o p e r p a t h ( / L i b r a r y / D e v e l o p e r / C o m m a n d L i n e T o o l s ) решение Принимать решение

Причина в том, что после обновления до версии macOS Sierra инструменты командной строки бесполезны.

введите команду xcode-select --install



Нажмите "Установить" и дождитесь завершения установки программного обеспечения.

Закройте командное окно и перезапустите brew install mongdb

3. Настройте MongoDB:

После установки MongoDB вам необходимо настроить MongoDB, иначе сервер не запустится.

(1) Создайте папку data / db в корневом каталоге:
mkdir -p /data/db

- p Может быть именем пути. В настоящее время, если некоторые каталоги в пути еще не существуют, после добавления этой опции система автоматически создаст те каталоги, которые еще не существуют, то есть одновременно можно создать несколько каталогов.

sudo mkdir -p /data/db

(2) Предоставьте разрешения для папки / data / db:

sudo chown id -u /data/db

(3) Добавьте переменные среды:
Откройте файл .zshrc;

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

Выполните команду, чтобы переменная среды вступила в силу:

(4) Измените файл конфигурации MongoDB, файл конфигурации по умолчанию mongod.conf в / usr / local / etc: vim /usr/local/etc/mongod.conf

Запускаем сервер:

На этом этапе выполните mongod, чтобы запустить службу mongodb: mongod



Когда появляются слова "ожидает подключения к порту 27017", наш сервер успешно запущен, он работает и прослушивает порт 27017.

Таким образом, вы можете начать взаимодействие с сервером, например, просто откройте новую вкладку терминала и запустите mongo, который откроет интерактивную консоль mongo и подключится к серверу по умолчанию (localhost: 27017):



До сих пор наш сервер был успешно запущен, а затем мы можем продолжить, ввести show dbs и другие команды, чтобы попробовать

В дальнейшем перезапустите сервис mongodb и введите командную строку mongodb:

Выполнить в окне iTerm2: mongod //MongoDB starting…waiting for connections
Выполняется другое окно iTerm2: mongo //MongoDB shell

Завершите процесс, запущенный на порту, который в большинстве случаев является процессом mongodb.

npx kill-port 27017

Общие команды Mongodb

1. База данных

Просмотреть все базы данных, Вы можете использовать команду: show dbs

Просмотр базы данных, подключенной в данный момент : db

MongoDB создать базу данных / переключатель : use DATABASE_NAME

Если база данных не существует, создайте базу данных, в противном случае переключитесь на указанную базу данных.

Вновь созданная база данных отображается в списке баз данных. Чтобы отобразить ее, нам нужно вставить некоторые данные во вновь созданную базу данных.

MongoDB удалить базу данных : db.dropDatabase()

Сначала просмотрите все базы данных: show dbs

Затем мы переключаемся на базу данных, которую вы хотите удалить, например: runoob: use runoob

Выполните команду удаления:

Наконец, проходим show dbs База данных команд успешно удалена:

2. Сбор

Просмотреть существующую коллекцию: show collections команда

Создать коллекцию : db.createCollection("CollectionName")

Создайте фиксированную коллекцию mycol, общий объем коллекции составляет 6142800 КБ, а максимальное количество документов - 10 000.

В MongoDB вам не нужно создавать коллекции. Когда вы вставляете несколько документов, MongoDB автоматически создает коллекцию.

Примечание: xyz_persist - мое локальное имя пользователя, вы должны изменить его на свое собственное имя пользователя.

1. Установите mongodb


Выполните команду brew install mongodb
Подождите немного, установка прошла успешно, как показано на рисунке:

2. Запустите mongodb

Выполните команду sudo mongod --config /usr/local/etc/mongod.conf, чтобы запустить службу.
Затем введите mongo во втором окне, вы можете использовать базу данных

Два, установка установочного пакета

1. Загрузите установочный пакет mongodb

2. Разархивируйте на локальный

Измените имя распакованной папки на mongodb (custom)

3. Создайте новую папку в том же каталоге, что и bin.

Структура файловых каталогов следующая:






Отредактируйте etc / mongo.conf следующим образом


После ввода нажмите esc: wq для сохранения и выхода.

4. Измените переменную системной среды PATH.

Добавьте каталог / Users / xyz_persist / Public / mongodb / bin в PATH

echo 'export PATH=/Users/xyz_persist/Public/mongodb/bin:$PATH'>>

После добавления, чтобы переменная среды вступила в силу, вы можете перезапустить терминал оболочки или ввести источник команды .bash_profile

Файл .bash_profile находится в / Users / xyz_persist

5. Войдите в каталог bin и запустите файл конфигурации.

Введите ./mongod для запуска, не случайно, выдается ошибка

exception in initAndListen: 29 Data directory /data/db not found., terminating


Путь к dbpath для запуска Mongod по умолчанию - / data / db, на этом компьютере нет этого каталога

1. Создайте каталог db

sudo mkdir /data

sudo mkdir /data/db

2. Измените права доступа к папке на чтение и запись.

sudo chmod 777 data/db

Перезагрузите в каталоге / bin

После успешного запуска в последней строке должен быть номер порта, как показано на рисунке.


Создайте новое окно, введите ./mongo, управляйте базой данных



✌️ Нет проблем

Читайте также: