как установить mongodb на windows 10
Как установить mongodb на windows 10
Для установки MongoDB загрузим один распространяемых пакетов с официального сайта https://www.mongodb.com/try/download/community.
Для загрузки нобходиомго функционала выберем нужную операционную систему и подходящий тип пакета. Рассмотрим на примере установки на ОС Windows.
MongoDB можно загрузить в ряде вариантов. Так, для Windows доступна загрузка установщика msi и также доступна загрузка zip-пакета. В реальности нам достаточно загрузить zip-архив и распаковать в нужной нам папке. Поэтому выберем этот вариант загрузки:
Если до установки уже была установлена более ранняя версия MongoDB, то ее необходимо удалить.
Содержимое пакета MongoDB
Если после установки мы откроем папку bin в распакованном архиве ( C:\mongodb\bin ), то сможем найти там кучу приложений, которые выполняют определенную роль. Вкратце рассмотрим их.
mongo : представляет консольный интерфейс для взаимодействия с базами данных, своего рода консольный клиент
mongod : сервер баз данных MongoDB. Он обрабатывает запросы, управляет форматом данных и выполняет различные операции в фоновом режиме по управлению базами данных
mongos : служба маршрутизации MongoDB, которая помогает обрабатывать запросы и определять местоположение данных в кластере MongoDB
Создание каталога для БД и запуск MongoDB
После установки надо создать на жестком диске каталог, в котором будут находиться базы данных MongoDB.
Командная строка отобразит нам ряд служебной информации, например, что сервер запускается на localhost на порту 27017.
Это консольная оболочка для взаимодействия с сервером, через которую можно управлять данными. Второй строкой эта оболочка говорит о подключении к серверу mongod.
Теперь поизведем какие-либо простейшие действия. Введем в mongo последовательно следующие команды и после каждой команды нажмем на Enter:
С помощью метода db.users.insertOne() в коллекцию users базы данных test добавляется объект < name: "Tom" >. Описание добавляемого объекта определяется в формате, с которым вы возможно знакомы, если имели дело с форматом JSON. То есть в данном случае у объекта определен один ключ «name», которому сопоставляется значение «Tom». То есть мы добавляем пользователя с именем Tom.
Если объект был успешно добавлен, то консоль выведет результат операции, в частности, идентификатор добавленного объекта.
А третья команда db.users.find() выводит на экран все объекты из бд test.
Установка драйверов MongoDB
На офсайте на странице https://docs.mongodb.com/ecosystem/drivers/ можно найти список драйверов для всех поддерживаемых языков программирования, в частности, для PHP, C, C++, C#, Java, Go, Python, Rust, Ruby, Scala, Swift, а также для Node.js.
Работа с драйверами на конкретных языках программирования будет рассмотрена в соответствующих разделах, посвященных этим языкам..
Install MongoDB Community Edition on WindowsВ¶
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 4.4 Community Edition on Windows using the default installation wizard.
MongoDB VersionВ¶
Installation MethodВ¶
This tutorial installs MongoDB on Windows using the default MSI installation wizard. To install MongoDB using the msiexec.exe command-line tool instead, see Install MongoDB using msiexec.exe. The msiexec.exe tool is useful for system administrators who wish to deploy MongoDB in an unattended fashion using automation.
ConsiderationsВ¶
Platform SupportВ¶
MongoDB 4.4 Community Edition supports the following 64-bit versions of Windows on x86_64 architecture:
MongoDB only supports the 64-bit versions of these platforms.
See Supported Platforms for more information.
VirtualizationВ¶
Oracle offers experimental support for VirtualBox on Windows hosts where Hyper-V is running. However, Microsoft does not support VirtualBox on Hyper-V.
Disable Hyper-V if you want to install MongoDB on Windows using VirtualBox.
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В¶
ProcedureВ¶
Download the installer.В¶
Run the MongoDB installer.В¶
For example, from the Windows Explorer/File Explorer:
Follow the MongoDB Community Edition installation wizard.В¶
The wizard steps you through the installation of MongoDB and MongoDB Compass.
Starting in MongoDB 4.0, you can set up MongoDB as a Windows service during the install or just install the binaries.
If You Installed MongoDB as a Windows ServiceВ¶
The MongoDB service is started upon successful installation [ 1 ].
To begin using MongoDB, connect a mongo.exe shell to the running MongoDB instance. Either:
Or, open a Command Interpreter with Administrative privileges and run:
For information on CRUD (Create,Read,Update,Delete) operations, see:
If You Did Not Install MongoDB as a Windows ServiceВ¶
If you only installed the executables and did not install MongoDB as a Windows service, you must manually start the MongoDB instance.
Run MongoDB Community Edition as a Windows ServiceВ¶
Start MongoDB Community Edition as a Windows ServiceВ¶
To start/restart the MongoDB service, use the Services console:
To begin using MongoDB, connect a mongo.exe shell to the running MongoDB instance. To connect, open a Command Interpreter with Administrative privileges and run:
For more information on connecting a mongo.exe shell, such as to connect to a MongoDB instance running on a different host and/or port, see The mongo Shell. For information on CRUD (Create,Read,Update,Delete) operations, see:
Stop MongoDB Community Edition as a Windows ServiceВ¶
To stop/pause the MongoDB service, use the Services console:
Remove MongoDB Community Edition as a Windows ServiceВ¶
Run MongoDB Community Edition from the Command InterpreterВ¶
You can run MongoDB Community Edition from the Windows command prompt/interpreter ( cmd.exe ) instead of as a service.
Create database directory.В¶
Create the data directory where MongoDB stores data. MongoDB’s default data directory path is the absolute path \data\db on the drive from which you start MongoDB.
Start your MongoDB database.В¶
If the MongoDB database server is running correctly, the Command Interpreter displays:
Depending on the Windows Defender Firewall settings on your Windows host, Windows may display a Security Alert dialog box about blocking «some features» of C:\Program Files\MongoDB\Server\4.4\bin\mongod.exe from communicating on networks. To remedy this issue:
To learn more about security and MongoDB, see the Security Documentation.
Connect to MongoDB.В¶
To connect a mongo.exe shell to the MongoDB instance, open another Command Interpreter with Administrative privileges and run:
For more information on connecting a mongo.exe shell, such as to connect to a MongoDB instance running on a different host and/or port, see The mongo Shell. For information on CRUD (Create,Read,Update,Delete) operations, see:
Additional ConsiderationsВ¶
Localhost Binding by DefaultВ¶
This value can be configured either:
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.
Upgrading a full release series (e.g. 4.0 to 4.2) requires a new installation.
Add MongoDB binaries to the System PATHВ¶
All command-line examples in this tutorial are provided as absolute paths to the MongoDB binaries. You can add C:\Program Files\MongoDB\Server\4.4\bin to your System PATH and then omit the full path to the MongoDB binaries.
Install MongoDB Community on Windows using msiexec.exe В¶
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 Windows in an unattended fashion using msiexec.exe from the command line. This is useful for system administrators who wish to deploy MongoDB using automation.
MongoDB VersionВ¶
Installation MethodВ¶
ConsiderationsВ¶
MongoDB Shell, mongosh В¶
The MongoDB Shell (mongosh) is not installed with MongoDB Server. You need to follow the mongosh installation instructions to download and install mongosh separately.
Platform SupportВ¶
MongoDB 5.0 Community Edition supports the following 64-bit versions of Windows on x86_64 architecture:
MongoDB only supports the 64-bit versions of these platforms.
See Supported Platforms for more information.
VirtualizationВ¶
Oracle offers experimental support for VirtualBox on Windows hosts where Hyper-V is running. However, Microsoft does not support VirtualBox on Hyper-V.
Disable Hyper-V if you want to install MongoDB on Windows using VirtualBox.
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В¶
ProcedureВ¶
Download the installer.В¶
Install MongoDB Community Edition on WindowsВ¶
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 Windows using the default installation wizard.
MongoDB VersionВ¶
Installation MethodВ¶
This tutorial installs MongoDB on Windows using the default MSI installation wizard. To install MongoDB using the msiexec.exe command-line tool instead, see Install MongoDB using msiexec.exe. The msiexec.exe tool is useful for system administrators who wish to deploy MongoDB in an unattended fashion using automation.
ConsiderationsВ¶
MongoDB Shell, mongosh В¶
The MongoDB Shell (mongosh) is not installed with MongoDB Server. You need to follow the mongosh installation instructions to download and install mongosh separately.
Platform SupportВ¶
MongoDB 5.0 Community Edition supports the following 64-bit versions of Windows on x86_64 architecture:
MongoDB only supports the 64-bit versions of these platforms.
See Supported Platforms for more information.
VirtualizationВ¶
Oracle offers experimental support for VirtualBox on Windows hosts where Hyper-V is running. However, Microsoft does not support VirtualBox on Hyper-V.
Disable Hyper-V if you want to install MongoDB on Windows using VirtualBox.
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В¶
ProcedureВ¶
Download the installer.В¶
Run the MongoDB installer.В¶
For example, from the Windows Explorer/File Explorer:
Follow the MongoDB Community Edition installation wizard.В¶
The wizard steps you through the installation of MongoDB and MongoDB Compass.
Starting in MongoDB 4.0, you can set up MongoDB as a Windows service during the install or just install the binaries.
Install mongosh В¶
If You Installed MongoDB as a Windows ServiceВ¶
If You Did Not Install MongoDB as a Windows ServiceВ¶
If you only installed the executables and did not install MongoDB as a Windows service, you must manually start the MongoDB instance.
Run MongoDB Community Edition as a Windows ServiceВ¶
If you have not already done so, follow the mongosh installation instructions to download and install the MongoDB Shell (mongosh).
Be sure to add the path to your mongosh.exe binary to your PATH environment variable during installation.
Open a new Command Interpreter and enter mongosh.exe to connect to MongoDB.
For more information on connecting to a mongod using mongosh.exe, such as connecting to a MongoDB instance running on a different host and/or port, see Connect to a Deployment.
For information on CRUD (Create, Read, Update, Delete) operations, see:
Start MongoDB Community Edition as a Windows ServiceВ¶
To start/restart the MongoDB service, use the Services console:
Stop MongoDB Community Edition as a Windows ServiceВ¶
To stop/pause the MongoDB service, use the Services console:
Remove MongoDB Community Edition as a Windows ServiceВ¶
Run MongoDB Community Edition from the Command InterpreterВ¶
You can run MongoDB Community Edition from the Windows command prompt/interpreter ( cmd.exe ) instead of as a service.
Create database directory.В¶
Create the data directory where MongoDB stores data. MongoDB’s default data directory path is the absolute path \data\db on the drive from which you start MongoDB.
Start your MongoDB database.В¶
If the MongoDB database server is running correctly, the Command Interpreter displays:
Depending on the Windows Defender Firewall settings on your Windows host, Windows may display a Security Alert dialog box about blocking «some features» of C:\Program Files\MongoDB\Server\5.0\bin\mongod.exe from communicating on networks. To remedy this issue:
To learn more about security and MongoDB, see the Security Documentation.
Connect to MongoDB.В¶
If you have not already done so, follow the mongosh installation instructions to download and install the MongoDB Shell (mongosh).
Be sure to add the path to your mongosh.exe binary to your PATH environment variable during installation.
Open a new Command Interpreter and enter mongosh.exe to connect to MongoDB.
For more information on connecting to mongod using mongosh.exe, such as connecting to a MongoDB instance running on a different host and/or port, see Connect to a Deployment.
For information on CRUD (Create, Read, Update, Delete) operations, see:
Additional ConsiderationsВ¶
Localhost Binding by DefaultВ¶
This value can be configured either:
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.
Upgrading a full release series (e.g. 4.0 to 4.2) requires a new installation.
Add MongoDB binaries to the System PATHВ¶
If you add C:\Program Files\MongoDB\Server\5.0\bin to your System PATH you can omit the full path to the MongoDB Server binaries. You should also add the path to mongosh if you have not already done so.
Install MongoDBВ¶
Author: MongoDB Documentation Team
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.
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.
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.В¶
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.В¶
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.
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 :
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.В¶
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.
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
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: