Как установить mongodb на windows 10

Установка и запуск MongoDB на Windows 10.В первую очередь необходимо скачать MongoDB с официального сайта.После перехода по ссылке на официальный сайт перед вами будет представлена форма, в которой необходимо указать требуемую версию системы управления базами данных, вашу версию операционной

Данный материал предоставлен сайтом
PacificSky.Ru исключительно в ознакомительных целях. Администрация не несет ответственности за его содержимое.

Установка и запуск MongoDB на Windows 10.

В первую очередь необходимо

скачать MongoDB

с официального сайта.
После перехода по ссылке на официальный сайт перед вами будет представлена форма, в которой необходимо указать требуемую версию системы управления базами данных, вашу версию операционной системы, тип устанавливаемого пакета и нажать кнопку «Download» для скачивания.

После того как файл будет скачан, приступаем к установке:
Начиная с версии 4.0, MongoDB можно настроить и запустить как службу Windows в процессе установки.
Сама служба MongoDB будет запущена после успешной установки.
Для запуска MongoDB как службы в процессе установки необходимо отметить checkbox с пунктом: «Install MongoD as service».
Так-же вы можете установить MongoDB со своими параметрами или оставить все по умолчанию.

После выполнения установки MongoDB будет запущена как служба и будет доступна для работы с ней.
Если по каким то причинам вы не хотите запускать MongoDB как службу, то необходимо убрать галочку с «Install MongoD as service».

Запуск MongoDB из CMD консольного интерпретатора моманд.

  1. Создайте каталог данных, в котором MongoDB будет хранить данные.
    По умолчанию это должен быть абсолютный путь — «C:datadb».
    Для этого создайте на диске «C» папку с названием «data» и внутри папки дата создайте папку «db«.
  2. Для старта MongoDB необходимо запустить файл mongod.exe с указанием пути к базе данных.
    Для этого запустить «cmd» консоль и выполните команду:
    "C:Program FilesMongoDBServer4.2binmongod.exe" --dbpath="c:datadb"

    .

  3. Для соединения с базой данных откройте еще одну «cmd» консоль и выполните команду:
    "C:Program FilesMongoDBServer4.2binmongo.exe"

Последнее обновление: 27.07.2022

Установка сервера Mongod

Официальный сайт предоставляет пакеты дистрибутивов для различных платформ: Windows, Linux, MacOS, Solaris. И каждой платформы доступно несколько дистрибутивов.
Причем есть два вида серверов — бесплатный Community и платный Enterprise. В данном руководстве будем использовать бесплатную версию Community.

Для установки MongoDB загрузим один распространяемых пакетов с официального сайта https://www.mongodb.com/try/download/community.

Для загрузки всех необходимых файлов выберем нужную операционную систему и подходящий тип пакета. Рассмотрим на примере установки на ОС Windows.

MongoDB можно загрузить в ряде вариантов. Так, для Windows доступна загрузка установщика msi и также доступна загрузка zip-пакета. В реальности нам достаточно загрузить
zip-архив и распаковать в нужной нам папке. Поэтому выберем этот вариант загрузки:

Установка MongoDB

(В случае если на стороне сайта mongodb.com есть ограничения по региональному признаку, можно использовать VPN для входя на сайт или загрузить все необходимые
файлы по прямой ссылке, например, ссылка для пакета mongodb 6.0.0 для Windows:
https://fastdl.mongodb.org/windows/mongodb-windows-x86_64-6.0.0.zip)

Альтернативная ссылка на пакет для WIndows: mongodb-windows-x86_64-6.0.0.zip

Если до установки уже была установлена более ранняя версия MongoDB, то ее необходимо удалить.

После загрузки архивного пакета распакуем его в папку C:mongodb.

Если после установки мы откроем папку bin в распакованном архиве (C:mongodbbin), то сможем найти там кучу приложений, которые выполняют определенную роль. Вкратце рассмотрим их.

Каталог MongoDB

  • mongod: сервер баз данных MongoDB. Он обрабатывает запросы, управляет форматом данных и выполняет различные
    операции в фоновом режиме по управлению базами данных

  • mongos: служба маршрутизации MongoDB, которая помогает обрабатывать запросы и определять местоположение данных в кластере
    MongoDB

Создание каталога для БД и запуск MongoDB

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

В ОС Windows по умолчанию MongoDB хранит базы данных по пути C:datadb, поэтому, если вы используете Windows, вам надо создать
соответствующий каталог.

Если же возникла необходимость использовать какой-то другой путь к файлам, то его можно передать при запуске MongoDB во флаге
--dbpath.

Итак, после создания каталога для хранения БД можно запустить сервер MongoDB. Сервер представляет приложение mongod, которое находится
в каталоге bin в папке сервера. Для этого запустим терминал/командную строку и там введем соответствующие команды. Для ОС Windows это
будет выглядеть так:

Запуск сервера MongoDB mongod

Командная строка отобразит нам ряд служебной информации, например, что сервер запускается на localhost на порту 27017.

И после удачного запуска сервера мы сможем производить операции с бд через клиент.

Установка клиента Mongosh

Выше мы установили сервер MongoDb. Однако для работы с сервером нам нужен клиент. Наиболее простым клиентом в данном случае является MongoDB Shell или mongosh —
консольная оболочка для отправки запросов к серверу, которая также предоставляется непосредственно компанией MongoDB.

Для установки клиента перейдем по адресу https://www.mongodb.com/try/download/shell

Установка клиента MongoDB Shell

Здесь опять же мы можем выбрать версии клиента для разных операционных систем. Для Windows пакет клиента доступен в виде установщика msi и архива zip. В данном случае выберем архив zip.

Альтернативная ссылка на пакет для WIndows: mongosh-1.5.1-win32-x64.zip

Загруженный пакет распакуем в папку C:mongosh.

Если в распакованном архиве мы зайдем в папку bin (то есть C:mongoshbin), то обнаружим там консольную утилиту mongosh,
которая будет применяться для работы с сервером MongoDB:

Каталог клиента MongoDB Shell

Подключение к серверу из клиента

Используем выше установленное клиентское приложение mongosh для взаимодействия с сервером mongodb. (При работе с mongosh не стоит забывать, что у нас должен быть запущен сервер mongod).
Итак, запустим файл mongosh, который располагается в выше рассмотренной папке установки:

Запуск оболочки MongoDB Shell mongosh

При запуске программы mongosh вначале она спросит пользователя, какую строку подключения использовать для подключения к серверу MongoDB. В этом моменте просто нажмем на Enter,
чтобы использовать строку подключения к MongoDB по умолчанию. А по умолчанию сервер mongodb запускается на порту 27017,
а полная строка подключения выглядит следующим образом: mongodb://localhost:27017 или mongodb://127.0.0.1:27017

После подключения консоль отобразит ряд служебной информации и подключится к базе данных test.

Теперь поизведем какие-либо простейшие действия. Введем в консоль последовательно следующие команды и после каждой команды нажмем на Enter:

db.users.insertOne( { name: "Tom" } )
db.users.find()

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

С помощью метода db.users.insertOne() в коллекцию users базы данных test добавляется объект { name: "Tom" }.
Идентификатор db представляет текущую базу данных. В нашем случае мы подключены к базе данных по умолчанию — то есть к базе данных test,
соответственно db здесь представляет базу данных test. При этом не важно, есть или нет такая бд — если ее нет, то она создается

После db идет
users — это коллекция, в которую затем мы добавляем новый объект. Если в SQL нам надо создавать таблицы заранее, то коллекции
MongoDB создает самостоятельно при их отсутствии.

Описание добавляемого объекта определяется в формате, с которым вы возможно знакомы, если имели дело с форматом JSON. То есть в данном случае у объекта
определен один ключ «name», которому сопоставляется значение «Tom». То есть мы добавляем пользователя с именем Tom.

Если объект был успешно добавлен, то консоль выведет результат операции, в частности, идентификатор добавленного объекта.

А третья команда db.users.find() выводит на экран все объекты из бд test.

Добавление в бд MongoDB

Из вывода вы можете увидеть, что к начальным значениям объекта было добавлено какое-то непонятно поле ObjectId.
Как вы помните, MongoDB в качестве уникальных идентификаторов документа использует поле _id. И в данном случае ObjectId как
раз и представляет значение для идентификатора _id.

Установка драйверов MongoDB

В дальнейшем в рамках данного руководства мы будет рассматривать взаимодействие с сервером MongoDB преимущественно через выше использованную оболочку
mongo. Однако, мы также можем взаимодействовать с mongodb в наших приложениях, написанных на PHP, C++, C# и других языках программирования. И для этой цели необходим специальный драйвер.

На офсайте на странице https://docs.mongodb.com/ecosystem/drivers/ можно найти список драйверов
для всех поддерживаемых языков программирования, в частности, для PHP, C, C++, C#, Java, Go, Python, Rust, Ruby, Scala, Swift, а также для Node.js.

Работа с драйверами на конкретных языках программирования будет рассмотрена в соответствующих разделах, посвященных этим языкам..

MongoDB is an open-source and widely used document-oriented NoSQL database that is designed to store a large scale of data. It offers JSON-like documents, ad hoc queries, indexing, and real-time aggregation, which makes it popular in the database world and also allows you to work with that data very efficiently. With the growing popularity of MongoDB, it has become essential for web developers to install and use MongoDB on their systems.

In this article, we will tell you everything on how to download and install MongoDB in Windows 10. You can go through KnowledgeHut’s web application development course to learn how to create a web application using the MongoDB database and get yourself the job of your dreams. This extensive guide will show you how to install MongoDB 6.0.1 Community Edition in Windows 10. So let us get started. 

We will show you how to install MongoDB Community Edition on Windows 10 using the default method with the MSI installation wizard. 

The msiexec.exe tool is useful for system administrators who wish to deploy MongoDB in an unattended fashion using automation. 

Considerations

Before you download and install MongoDB on Windows, you must consider some considerations.

1. Install MongoDB Shell Separately

MongoDB Shell (mongosh) does not come with the MongoDB Community Edition. You need to install it separately after successfully installing the MongoDB server on your windows 10 system.

2. Platform Support

MongoDB 6.0 Community Edition requires x86_64 architecture to function correctly.

It supports 64-bit versions of the following Windows versions:

  • Windows Server 2019 
  • Windows 10 / Windows Server 2016 

3. Virtualization

Microsoft does not support VirtualBox on Hyper-V by default.

If you want to install MongoDB on VirtualBox, then you need to disable Hyper-V in windows.

Follow the following steps to disable Hyper-V in Windows 10: 

  • Go to Control Panel 
  • Select “Programs and Features” 
  • Select «Turn Windows features on or off» on the left side 
  • In the Windows Features menu, navigate to Hyper-V > Hyper-V Platform and uncheck the Hyper-V Hypervisor check box. 
  • Click OK to save changes 

4. Production Notes 

If you need to optimize database performance further, you can read the MongoDB production notes and deploy the configuration recommendations. 

Prerequisites 

Before downloading and installing MongoDB, you must fulfill the minimum MongoDB system requirements to avoid any errors and poor performance.

Given below are the hardware and software requirements for MongoDB: 

1. Hardware Requirements

For Intel x86_64 architecture, MongoDB requires: 

  • Sandy Bridge or later processor 
  • Tiger Lake, Celeron, or Pentium processor. 

 For AMD x86_64 architecture, MongoDB requires:

  • Bulldozer or later processor. 

2. Software Requirements

  • Windows Server 2019 
  • Windows 10 / Windows Server 2016 

How to Download MongoDB for Windows 10?

Here’s a step-by-step guide to download MongoDB for windows 10 64-bit msi installer file.

Step 1: Go to the Official MongoDB website

Step 2: Navigate to Products > Community Edition 

Step 3: Select the appropriate installer file from the dropdown menus on the Community Edition page.

  • In the version dropdown, select the latest version, 6.0.1(current) 
  • In the Platform dropdown, select Windows 
  • In the Package dropdown, select msi 

How to Download MongoDB for Windows 10?

Step 4: Click the green «Download» button. Wait for 2-5 minutes for the file to download. (Depending on your internet speed) 

How to Install MongoDB on Windows 10 [Step-by-Step]?

After the installer file has been downloaded, it’s time to run the installer file. 

Procedure  

Step: 1: Go to the downloaded directory in your system (by default, it should be in the `Downloads` directory). 

Step 2: Double-click on the .msi file. It will open the MongoDB setup windows. 

MongoDB setup window

Step 3: It will open the MongoDB Community Edition installation wizard. This setup wizard guides you through the installation of MongoDB in your system. To continue the process, click «Next.» 

MongoDB setup end-user license

Step 4: Read the End-User License Agreement, accept the terms and conditions, and then click the «Next» button to continue. 

MongoDB setup options

Step 5: Next, you can choose either the Complete setup or Custom setup type to proceed. But for a beginner, we’d recommend using the Complete setup option. It installs MongoDB in the default location. Select the Complete setup, and click «Next.» 

MongoDB setup configuration

 

Step 6: Select the «Install MongoD as a Service» option on the next page. Keep all other parameters as default. Click on the «Next» button.

MongoDB compass setup

Step 7: In the next step, you will get an option to install MongoDB compass. Uncheck it if you don’t want MongoDB compass to be installed on your device, and then click the «Next» button. 

MongoDB installation

Step 8: In the «Ready to install MongoDB» page, click the «Install» button, give administrator access, and wait for the installation to finish. Once installation is complete, you can click on the «Finish» button to finalize your installation. 

How to Install mongosh MongoDB Shell in Windows 10?

MongoDB installer does not include mongosh, which is a MongoDB Shell used for interacting with MongoDB deployments. You need to install it separately.

Here’s a step-by-step guide to installing it: 

Step 1: Open the MongoDB Download Center from this link 

mongoose download center

Step 2: Select Windows 64-bit (8.1+) (MSI) in the Platform dropdown menu 

Step 3: Click on the Download button, and wait for the download. 

Step 4: Go to the download directory, and double-click the installer file. 

Step 5: Follow the installation prompts to install mongosh 

Set up Environment Variable

Before you can run the MongoDB server, you have to add the MongoDB path as an environment variable.

Step 1: Go to the MongoDB installation directory in the “C Drive.» Navigate to Server > 6.0 > bin folder. Copy the path. It will look like this:

C:Program FilesMongoDBServer6.0bin 

MongoDB copy bin path

Step 2: Go to Windows Search for «Environment Variables» and open the option «Edit environment variables for your account» option.

Open ‘Edit the system environment variables’ in Windows 10

Step 3: Click on the «Environment Variable..»

Open environment variables

Step 4: On the System variables, find the «Path» option. Double-click on it.

Set environment variables for MongoDB

Step 5: Click on «New» to set a new path variable.

Set environment variables for MongoDB

Step 6: Paste the copied path here, and press «OK.» Now you can run the MongoDB local server from any path in the terminal of your computer. 

How to Check If MongoDB is Installed?

After you’ve added the environment variable in the system, you can run the `mongod –version`  command on the Command window to check if MongoDB is installed correctly. It should give a result like this: 

C:UsersArnabDesktop> mongod --version 
db version v5.0.9 
Build Info: { 
"version": "5.0.9", 
"gitVersion": "6f7dae919422dcd7f4892c10ff20cdc721ad00e6", 
"modules": [], 
"allocator": "system", 
"environment": { 
"distarch": "x86_64", 
"target_arch": "x86_64" 
} 
} 

How to Create a Demo Database on MongoDB?

Now that you’ve successfully installed MongoDB and mongoose shell in your system, here’s a step-by-step guide to creating a demo database to check if the database is appropriately working.

Step 1: Open the command prompt on your desktop, and type `mongosh` to start the MongoDB server. The screen will look like this. 

Start MongoDB local server

Step 2: Type `show dbs` to see the existing databases.

Show database

Step 3: To create a new database, just type `use ` For example, `use Knowledgehut` and hit enter.

Create new database

Step 4: To create a collection, you can type the following command. `db.createCollection(“”)`. For example, we can create a collection of students by typing `db.createCollection(“students”)` 

Create new collection

Step 5: Then, you can insert new data by typing `db.students.insertOne({«name»:» John», «title»:» Doe»})`

Add data to collection

Step 6: Now you can type `show dbs` to see all the databases, including the new one you just created.

Show database

How to Uninstall MongoDB in Windows 10? 

Here are the steps you need to follow to uninstall MongoDB from Windows 10: 

Step 1: Go to the control panel. 

Step 2: Then go to the Programs and Features section 

How to Uninstall MongoDB in Windows 10

Step 3: Select MongoDB from the list and double-click on it, and a prompt will appear asking you to confirm the uninstallation. 

Step 4: Click OK and wait for the uninstallation. Your system will restart.

How to Uninstall MongoDB in Windows 10

With that, you have successfully uninstalled MongoDB from Windows 10. 

Navigate to Programs and Features

To verify whether you’ve successfully uninstalled MongoDB from your system, you can open the Command window and type the following command: `mongod –version`. If it shows that «mongod is not recognized as an internal or external command,» you’ve successfully uninstalled MongoDB from your Windows 10 system.

Conclusion 

MongoDB has garnered quite a lot of attention among developers and designers across the globe, owing to its numerous advantages over other SQL-based databases. 

Not to mention that it’s extremely easy to install on your Windows 10 computer. 

Just download the installation files, launch it accordingly and follow the steps mentioned in detail to install MongoDB on your Windows 10.

If you want to learn more, go to KnowledgeHut’s web application development course, and you’ll learn everything you need to know about using the MongoDB database to create cloud-based applications.

Once done, test the newly installed application to check if it works appropriately as per your need. If not, make sure to follow the above-mentioned steps carefully to ensure that you’ve followed all the steps correctly. 

Frequently Asked Questions (FAQs)

1. How Do You Install MongoDB on Windows Using CMD?

Here is a step-by-step guide to installing MongoDB on Windows using CMD: 

1. Step 1 Open Your Browser and navigate to MongoDB Download Center. 

2. Step 2: Select the appropriate installer file from the dropdown menus.

  • In the version dropdown, select the latest version, 6.0.1(current) 
  • In the Platform dropdown, select Windows 
  • In the Package dropdown, select MSI. 

3. Go to the Downloads folder, and open the Windows Command Interpreter. 

4. Here, run the following command: `msiexec.exe /l*v mdbinstall.log /qb /i mongodb-windows-x86_64-6.0.1-signed.msi`, and press enter.

5. This will install MongoDB in the default directory «C:Program FilesMongoDBServer6.0bin.” 

2. Can You Install MongoDB on Windows? 

You can easily install MongoDB on a Windows system by following our step-by-step guide. Just check the system requirements before installing it on Windows. 

3. Can I Run MongoDB Locally? 

If you install the MongoDB community edition in your system, you can run MongoDB locally. However, you must consider that you can access the database only on your local machine. It’s not accessible via the internet.

4. How Do I Start MongoDB in Windows Automatically? 

When installing MongoDB on your Windows 10 machine, choose the option to install MongoDB as a service. This will run MongoDB automatically when your machine is booting up. 

5. How To Check MongoDB Version in Windows? 

Open your command prompt, and type the following command: `mongod –version`. It will show the MongoDB version installed on your machine.

Nowadays we can find that the popularity of Structured Query Language(SQL) is getting decreased and the NoSQL database programs are taking place of it. Discussing with NoSQL databases, the popular one MongoDB a cross-platform document-oriented database program. MongoDB stores the data as JSON like documents other than tables in SQL. It is much easier to install MongoDB on Linux/Mac platforms using terminal commands. But Windows is mostly based Graphical User Interface(GUI)  and we need to do most of the tasks using GUI.

1. Download the Installation File

We can download the latest version of the MongoDB community edition from the link below.

https://fastdl.mongodb.org/win32/mongodb-win32-x86_64-2008plus-ssl-4.0.5.zip

Note:-

With the above link, we can download the MongoDB 4.0.5 version. The latest version of MongoDB can be downloaded from the official website URL below.

https://www.mongodb.com/download-center/community

The link below will download a zip file. Just extract the zip file.

2. Paste the MongoDB Folder Inside C drive

Extract this zip file and paste the folder anywhere on your system. ( But Pasting this folder inside C drive will the better choice).

3. Create a Directory to Store Documents

Create a folder named data inside the same path we pasted the MongoDB folder (C drive) and create a folder named db inside it. Because the MongoDB stores the database as documents inside this db folder.

Path to the “db” directory

4. Running MongoDB

Running MongoDB in windows is easier. First, open the MongoDB folder and to /bin. We can see a mongod.exe file inside the directory.

MongoDB folder structure
MongoDB running…

5. Check the MongoDB is Running Fine

We can check that the MongoDB is running fine on our system with a browser tab. Just enter the address below and this will show a message “It looks like you are trying to access MongoDB over HTTP on the native driver port.”

http://localhost:27017
MongoDB running fine

6. Accessing the MongoDB Shell

We can access the MongoDB shell by opening the mongo.exe file inside the MongoDB directory.

MongoDB shell

Have a nice code !

Понравилась статья? Поделить с друзьями:
  • Как установить miracast на windows 10
  • Как установить miniconda на windows 10
  • Как установить mingw64 на windows 10
  • Как установить minecraft windows 10 edition без microsoft store
  • Как установить minecraft java edition на windows 10