install mongodb php windows
Install mongodb php windows
Для установки 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 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.
В© MongoDB, Inc 2008-present. MongoDB, Mongo, and the leaf logo are registered trademarks of MongoDB, Inc.
How to install MongoDB on Windows with PHP & XAMPP
Learn how to install MongoDB on Windows OS and configure with PHP on XAMPP.
There are a couple of tutorials out there already, but neither of them helped me set everything up 100%. Some of them are missing key explanations, some of them are a bit old. My tutorial presumes you know your way around XAMPP on Windows and you have it installed already.
Here’s how to install MongoDB on your local Windows machine with XAMPP in 5 easy steps:
Step 1. Download mongo driver
To download mongo driver for Windows visit pecl.php.net
Download the latest stable release by clicking on the DLL link. I used the latest stable release at the time, 2017-05-04, version 1.2.9.
On the next page there is a DLL list. It is vital to pick the right version. You need to pick depending on three things:
Here’s where to find out that information:
Below that, in the table, you will see list of other information. You need to find the value for the Architecture (x86 or x64) and Thread Safety (enabled or disabled).
Finally, you can choose a proper DLL to download.
In my case, I had:
When Thread Safety is enabled, you need to download Thread Safe (TS) version. So I downloaded file: 7.0 Thread Safe (TS) x86
Add following line into php.ini file:
Step 4. Restart XAMPP and refresh phpinfo.php page
When you restart XAMPP and refresh the phpinfo page, something like this should appear when you CTRL+F and type mongo:
If you don’t see that on your phpinfo page, you did something wrong so try to go back through previous steps.
You might also be interested in:
Step 5. Install MongoDB on Windows
a) Download latest MongoDB server version.
b) Choose custom setup type and install in the C:\mongodb folder.
c) Then create db folder within data folder on the C drive – C:\data\db
d) Start MongoDB by executing the following command in the CMD: C:\mongodb\bin\mongod.exe
That is it, you successfully installed MongoDB on Windows and configured it in XAMPP!
Just in case you need extra help with step 5, here is the entire process explained with images.
Step 6. Download and install RoboMongo
As an extra step I would recommend installing MongoDB management tool, such as RoboMongo, (it’s called Robo 3T now) to easily manage MongoDB on your machine. Just create connection and you are set to go.
Conclusion and additional resources
Hope you found this tutorial useful in the process of installing and configuring MongoDB on your Windows machine with XAMPP.
For the next step, I recommend checking out the following MongoDB online courses on Pluralsight:
These fantastic courses by Nuri Halperin helped me to learn a lot more about MongoDB.
MongoDB PHP DriverВ¶
IntroductionВ¶
The PHP driver consists of two components, the MongoDB extension and library.
The extension provides a low-level API and mainly serves to integrate libmongoc and libbson with PHP.
While it is possible to use the extension alone, users are strongly encouraged to use the extension and library together. The library provides a high-level API consistent with other MongoDB language drivers.
InstallationВ¶
First, make sure you have a recent version of PHP installed on your system. See the official PHP manual for download and installation instructions.
Install the PHP MongoDB Extension before installing the PHP Library for MongoDB. You can install the extension using PECL on the command line:
Finally, add the following line to your php.ini file:
On some systems, there may be multiple INI files for individual SAPIs (e.g. CLI, FPM). Make sure to enable the extension in all SAPIs that you need.
The preferred method of installing the PHP library is with Composer by running the following from your project root:
Additional installation instructions may be found in the library documentation.
Connect to MongoDB AtlasВ¶
To connect to a MongoDB Atlas cluster, use the Atlas connection string for your cluster:
For information about connecting to Atlas Serverless, see the Serverless Instance Limitations page for the minimum driver version you need.
Connect to a MongoDB Server on Your Local MachineВ¶
If you need to run a MongoDB server on your local machine for development purposes instead of using an Atlas cluster, you need to complete the following:
Always secure your MongoDB server from malicious attacks. See our Security Checklist for a list of security recommendations.
After you successfully start your MongoDB server, specify your connection string in your driver connection code.
If your MongoDB Server is running locally, you can use the connection string «mongodb://localhost:
is the port number you configured your server to listen for incoming connections.
If you need to specify a different hostname or IP address, see our Server Manual entry on Connection Strings.
To test whether you can connect to your server, replace the connection string in the Connect to MongoDB Atlas code example and run it.
CompatibilityВ¶
Due to potential problems representing 64-bit integers on 32-bit platforms, users are advised to use 64-bit environments. When using a 32-bit platform, be aware that any 64-bit integer read from the database will be returned as a MongoDB\BSON\Int64 instance instead of a PHP integer type.
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: