- Mongo tools install windows
- Содержимое пакета MongoDB
- Создание каталога для БД и запуск MongoDB
- Установка драйверов MongoDB
- Installing the Database Tools on WindowsВ¶
- OverviewВ¶
- VersioningВ¶
- CompatibilityВ¶
- MongoDB Server CompatibilityВ¶
- Platform SupportВ¶
- InstallationВ¶
- Download the Database Tools MSI installer.В¶
- Run the MSI installer.В¶
- Make the DB Tools available in your PATH .В¶
- Install MongoDB Community on Windows using msiexec.exe В¶
- OverviewВ¶
- MongoDB VersionВ¶
- Installation MethodВ¶
- ConsiderationsВ¶
- Platform SupportВ¶
- Production NotesВ¶
- Install MongoDB Community EditionВ¶
- ProcedureВ¶
- Download the installer.В¶
Mongo tools install windows
Для установки MongoDB загрузим один распространяемых пакетов с официального сайта https://www.mongodb.com/download-center/community.
Официальный сайт предоставляет пакеты дистрибутивов для различных платформ: Windows, Linux, MacOS, Solaris. И каждой платформы доступно несколько дистрибутивов. Причем есть два вида серверов — Community и Enterprise. В данном случае надо установить версию Community. Хотя Enterprise-версия обладает несколько большими возможностями, но она доступна только в триальном режиме или по подписке.
На момент написания данного материала последней версией платформы была версия 4.4 . Использование конкретной версии может несколько отличаться от применения иных версий платформы MongoDB.
Для загрузки нобходиомго функционала выберем нужную операционную систему и подходящий тип пакета:
Для ОС Windows можно выбрать тип пакета «ZIP», то есть загрузить сервер в виде архива.
Если до установки уже была установлена более рання версия MongoDB, то ее необходимо удалить и также необходимо удалить все равне созданные базы данных.
После загрузки архивного пакета распакуем его в папку C:\mongodb .
Содержимое пакета MongoDB
Если после установки мы откроем папку bin в распакованном архиве ( C:\mongodb\bin ), то сможем найти там кучу приложений, которые выполняют определенную роль. Вкратце рассмотрим их.
mongo : представляет консольный интерфейс для взаимодействия с базами данных, своего рода консольный клиент
mongod : сервер баз данных MongoDB. Он обрабатывает запросы, управляет форматом данных и выполняет различные операции в фоновом режиме по управлению базами данных
mongos : служба маршрутизации MongoDB, которая помогает обрабатывать запросы и определять местоположение данных в кластере MongoDB
Создание каталога для БД и запуск MongoDB
После установки надо создать на жестком диске каталог, в котором будут находиться базы данных MongoDB.
В ОС Windows по умолчанию MongoDB хранит базы данных по пути C:\data\db , поэтому, если вы используете Windows, вам надо создать соответствующий каталог. В ОС Linux и MacOS каталогом по умолчанию будет /data/db .
Если же возникла необходимость использовать какой-то другой путь к файлам, то его можно передать при запуске MongoDB во флаге —dbpath .
Итак, после создания каталога для хранения БД можно запустить сервер MongoDB. Сервер представляет приложение mongod , которое находится в папке bin. Для этого запустим командную строку (в Windows) или консоль в Linux и там введем соответствующие команды. Для ОС Windows это будет выглядеть так:
Командная строка отобразит нам ряд служебной информации, например, что сервер запускается на localhost на порту 27017.
И после удачного запуска сервера мы сможем производить операции с бд через оболочку mongo . Эта оболочка представляет файл mongo.exe , который располагается в выше рассмотренной папке установки. Запустим этот файл:
Это консольная оболочка для взаимодействия с сервером, через которую можно управлять данными. Второй строкой эта оболочка говорит о подключении к серверу mongod.
Теперь поизведем какие-либо простейшие действия. Введем в mongo последовательно следующие команды и после каждой команды нажмем на Enter:
Первая команда use test устанавливает в качестве используемой базу данных test. Даже если такой бд нет, то она создается автоматически. И далее db будет представлять текущую базу данных — то есть базу данных test. После db идет users — это коллекция, в которую затем мы добавляем новый объект. Если в SQL нам надо создавать таблицы заранее, то коллекции MongoDB создает самостоятельно при их отсутствии.
С помощью метода db.users.save() в коллекцию users базы данных test добавляется объект < name: "Tom" >. Описание добавляемого объекта определяется в формате, с которым вы возможно знакомы, если имели дело с форматом JSON. То есть в данном случае у объекта определен один ключ «name», которому сопоставляется значение «Tom». То есть мы добавляем пользователя с именем Tom.
Если объект был успешно добавлен, то консоль выведет результа в виде выражения WriteResult(< "nInserted" : 1 >) .
А третья команда db.users.find() выводит на экран все объекты из бд test.
Из вывода вы можете увидеть, что к начальным значениям объекта было добавлено какое-то непонятно поле ObjectId . Как вы помните, MongoDB в качестве уникальных идентификаторов документа использует поле _id . И в данном случае ObjectId как раз и представляет значение для идентификатора _id.
Установка драйверов MongoDB
Конечно, мы можем работать и через консоль mongo, добавляя и отображая объекты в бд. Но нам также было бы неплохо, если бы mongoDB взаимодействовала бы с нашими приложениями, написанными на PHP, C++, C# и других языках программирования. И для этой цели нам потребуются специальные драйверы.
На офсайте на странице https://docs.mongodb.com/ecosystem/drivers/ можно найти драйвера для таких языков программирования, как PHP, C++, C#, Java, Python, Perl, Ruby, Scala и др.
Далее уже, рассматривая взаимодействие отдельных языков программирования с MongoDB, мы подробнее рассмотрим установку и драйвера и всю необходимую конфигурацию для определенных языков программирования.
Installing the Database Tools on WindowsВ¶
OverviewВ¶
The MongoDB Database Tools are a suite of command-line utilities for working with MongoDB. Use this guide to install the Database Tools on the Windows platform.
VersioningВ¶
Starting with MongoDB 4.4, the MongoDB Database Tools are now released separately from the MongoDB Server and use their own versioning, with an initial version of 100.0.0 . Previously, these tools were released alongside the MongoDB Server and used matching versioning.
For documentation on the MongoDB 4.2 or earlier versions of these tools, reference the MongoDB Server Documentation for that version of the tool:
CompatibilityВ¶
MongoDB Server CompatibilityВ¶
MongoDB Database Tools version 100.3.1 supports the following versions of the MongoDB server:
- MongoDB 4.4
- MongoDB 4.2
- MongoDB 4.0
- MongoDB 3.6
While the tools may work on earlier versions of MongoDB server, any such compatibility is not guaranteed.
Platform SupportВ¶
The MongoDB Database Tools version 100.3.1 are supported on:
- Windows 8 and later
- Windows Server 2012 and later
InstallationВ¶
The MongoDB Database Tools can be installed with an MSI installer, or downloaded as a ZIP archive. Select the tab below depending on your desired installation method:
Download the Database Tools MSI installer.В¶
Open the MongoDB Download Center. Using the drop-down menu on the right-hand side of the page:
- Select the Windows x86_64 Platform
- Select the msi Package
- Click the Download button
Run the MSI installer.В¶
Double-click the downloaded MSI installer to install the Database Tools. During the install you may customize the installation directory if desired.
Make the DB Tools available in your PATH .В¶
You may wish to make the Database Tools available in your system’s PATH environment variable, which allows referencing each tool directly on the command prompt by name, without needing to specify its full path, or first navigating to its parent directory.
Once you’ve installed the Database Tools, follow the instructions below to add the install directory to your system’s PATH environment variable.:
- Open the Control Panel .
- In the System and Security category, click System .
- Click Advanced system settings . The System Properties modal displays.
- Click Environment Variables .
- In the System variables section, select Path and click Edit . The Edit environment variable modal displays.
- Click New and add the filepath to the location where you installed the Database Tools.
- Click OK to confirm your changes. On each other modal, click OK to confirm your changes.
Once set, you can run any of the Database Tools directly from your command prompt. Consult the reference page for the specific tool you wish to use for its full syntax and usage.
В© MongoDB, Inc 2008-present. MongoDB, Mongo, and the leaf logo are registered trademarks of MongoDB, Inc.
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 4.4 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В¶
This tutorial installs MongoDB 4.4 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.
Installation MethodВ¶
This tutorial installs MongoDB on Windows using the command-line tool msiexec.exe . To install MongoDB using the graphical MSI Installer instead, see Install MongoDB using the MSI Installer.
ConsiderationsВ¶
Platform SupportВ¶
- MongoDB 4.4 Community Edition removes support for Windows 8.1 / Server 2012 R2
- MongoDB 4.4 Community Edition removes support for Windows 8 / Server 2012
- MongoDB 4.4 Community Edition removes support for Windows 7 / Server 2008 R2
MongoDB 4.4 Community Edition supports the following 64-bit versions of Windows on x86_64 architecture:
- Windows Server 2019
- Windows 10 / Windows Server 2016
MongoDB only supports the 64-bit versions of these platforms.
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В¶
ProcedureВ¶
Follow these steps to install MongoDB Community Edition unattended on Windows from the Windows command prompt/interpreter ( cmd.exe ) using msiexec.exe .
Download the installer.В¶
Download the MongoDB Community .msi installer from the following link:
- In the Version dropdown, select the version of MongoDB to download.
- In the Platform dropdown, select Windows .
- In the Package dropdown, select msi .
- Click Download .