Enabling and Using MongoDB in ServBay (PHP Extension & Database Service)
ServBay is a powerful local web development environment designed specifically for developers. It not only integrates multiple web servers, programming languages, and databases, but it also comes bundled with many popular language extensions and tools. For PHP developers who need to work with the MongoDB database, ServBay provides a straightforward way to enable the PHP MongoDB extension and run the MongoDB database service.
This guide will walk you through enabling the PHP MongoDB extension in ServBay, starting the MongoDB database service, and demonstrate how to connect to and use MongoDB within a PHP project.
Overview: ServBay and MongoDB
MongoDB is a high-performance, open-source, document-oriented NoSQL database. Its flexible data model and excellent scalability make it widely adopted in modern web applications.
ServBay includes MongoDB as one of its built-in packages, allowing developers to easily deploy and manage MongoDB database instances in their local environment. In addition, ServBay compiles and packages the corresponding MongoDB extension (mongodb.so
) for various PHP versions, enabling PHP applications to interact with MongoDB databases.
To use MongoDB in your PHP project, you'll need to complete two main steps:
- Enable the PHP MongoDB extension: This allows your PHP code to call MongoDB-related functions.
- Start the MongoDB database service: This is the running instance of MongoDB responsible for storing and managing your data.
ServBay’s graphical user interface (GUI) makes these tasks simple and intuitive.
PHP MongoDB Extension Versions
ServBay provides the appropriate MongoDB extension for each supported PHP version. The specific extension versions may vary depending on ServBay updates, but typically stable versions compatible with corresponding PHP releases are available. Here are the common PHP versions and MongoDB extension versions in ServBay (please refer to your actual ServBay installation):
- PHP 5.6, 7.0: MongoDB 1.7.5
- PHP 7.1, 7.2, 7.3, 7.4: MongoDB 1.11.1
- PHP 8.0, 8.1, 8.2, 8.3: MongoDB 1.15.0
- PHP 8.4: MongoDB 1.19.1
Note: The PHP extension (mongodb.so
) simply provides the communication bridge between PHP and MongoDB. To actually interact with MongoDB in your PHP code, you should also install the official MongoDB PHP library, usually managed via Composer.
Enabling the PHP MongoDB Extension
To keep the environment streamlined, some PHP extensions in ServBay might not be enabled by default. The recommended way to enable the MongoDB extension is through the ServBay GUI.
Enabling via ServBay GUI
This is the easiest and fastest method:
- Open the ServBay app.
- In the left sidebar, click Languages, then select PHP.
- Choose the PHP version where you want to enable the MongoDB extension (e.g.,
PHP 8.4
). - On the right panel, locate the Extensions section.
- Scroll down to find the
MongoDB
extension. - Click the switch next to
MongoDB
to turn it from gray (disabled) to green (enabled). - Click the Save button at the bottom of the panel.
ServBay will automatically update the corresponding PHP configuration file and restart the affected PHP service to apply the changes.
Manually Editing Configuration Files (Optional)
If you prefer manual configuration or require advanced settings, you can directly edit the PHP configuration files. However, for most users, the GUI method is sufficient.
Locate the
conf.d
directory for your desired PHP version. For example, to enable the MongoDB extension for PHP 8.3, the typical path is:bash/Applications/ServBay/etc/php/8.3/conf.d/mongodb.ini
1Adjust the path according to your ServBay installation and PHP version.
Open the
mongodb.ini
file with a text editor.Find these lines:
ini[MongoDB] ; Uncomment the following line to enable MongoDB ;extension = mongodb.so
1
2
3Remove the semicolon
;
at the beginning of theextension = mongodb.so
line to uncomment it:ini[MongoDB] ; Uncomment the following line to enable MongoDB extension = mongodb.so
1
2
3Save the file.
Important: After manually editing the config file, you need to manually restart the relevant PHP service for the change to take effect. In the ServBay GUI, go to Packages in the left sidebar, find your modified PHP version, and click its restart button (usually a circular arrow icon) on the right.
Starting the MongoDB Database Service
Enabling the PHP extension only lets PHP code "talk" to MongoDB, but you’ll also need a running MongoDB database instance to actually store and process your data. ServBay packages MongoDB as a service, making it easy to start via the GUI.
- Open the ServBay app.
- In the left sidebar, click Packages.
- In the package list, go to the Databases category.
- Find the
MongoDB
package. - Click the switch next to
MongoDB
to turn it from gray (stopped) to green (running).
The MongoDB service will start and listen on the default port 27017
.
Verifying MongoDB Extension and Database Connection
Once you've completed the steps above, you can use the following methods to verify that the PHP MongoDB extension is loaded successfully and the MongoDB service is running properly.
Confirming the PHP Extension is Loaded
Create a simple PHP file to check the phpinfo()
output:
- In your ServBay website root directory (e.g.
/Applications/ServBay/www
), create a new PHP file such asphpinfo.php
. - Add the following content:php
<?php phpinfo(); ?>
1
2
3 - Access this file from your browser, for example,
https://servbay.demo/phpinfo.php
(assumingservbay.demo
is a site configured to point to the ServBaywww
directory). - On the
phpinfo
page, search for "MongoDB". If the extension is loaded, you'll see a section named "mongodb" with version info and configuration details.
(Note: The screenshot may differ slightly from your ServBay version or interface)
Testing Database Connection
Create a simple PHP script to connect to the locally running MongoDB database:
- Ensure you have installed the official MongoDB PHP library via Composer in your project. If not, navigate to your project folder and run:bash
composer require mongodb/mongodb
1 - Create a PHP file in your project, such as
test_mongodb.php
. - Add the following code:php
<?php require __DIR__ . '/vendor/autoload.php'; // Adjust path as needed for your project echo "Attempting to connect to MongoDB...\n"; try { // Connect to the locally running MongoDB instance on default port 27017 $client = new MongoDB\Client("mongodb://localhost:27017"); // List databases to verify the connection $listDatabases = $client->listDatabases(); echo "Successfully connected to MongoDB!\n"; echo "Available databases:\n"; foreach ($listDatabases as $databaseInfo) { echo "- " . $databaseInfo->getName() . "\n"; } } catch (\MongoDB\Driver\Exception\Exception $e) { echo "Failed to connect to MongoDB: " . $e->getMessage() . "\n"; } ?>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 - Run this script in the terminal (using the appropriate PHP version from ServBay) or access it via the web. If successful, you'll see a confirmation message and a list of databases. If it fails, the error message can help diagnose the issue (e.g., MongoDB service not running).
Using MongoDB in PHP Code
Once the PHP MongoDB extension is enabled and the MongoDB service is up, you can perform various database operations using the MongoDB PHP library installed via Composer.
Installing the MongoDB PHP Driver
As noted above, the recommended method is to use Composer to install the official MongoDB library:
composer require mongodb/mongodb
This installs the mongodb/mongodb
package and its dependencies, as well as generates the vendor/autoload.php
file.
Code Example
Here’s a simple example demonstrating how to connect to MongoDB, insert a document, and query for it:
<?php
require __DIR__ . '/vendor/autoload.php'; // Ensure you include Composer’s autoload file
echo "Connecting to MongoDB...\n";
try {
// Connect to the locally running MongoDB instance
$client = new MongoDB\Client("mongodb://localhost:27017");
// Select the database and collection
// If the database or collection does not exist, MongoDB will create it on first write
$collection = $client->servbay_demo_db->users; // Using 'servbay_demo_db' as a sample DB name
echo "Connected. Performing operations...\n";
// Insert a document
$insertResult = $collection->insertOne([
'name' => 'Alice ServBay', // Example data includes brand name
'email' => '[email protected]',
'age' => 30,
'createdAt' => new MongoDB\BSON\UTCDateTime(time() * 1000) // Use BSON date type
]);
printf("Inserted document with ID: %s\n", $insertResult->getInsertedId());
// Query a document
$document = $collection->findOne(['name' => 'Alice ServBay']);
echo "Found document:\n";
if ($document) {
print_r($document);
} else {
echo "Document not found.\n";
}
// Update a document (optional)
$updateResult = $collection->updateOne(
['name' => 'Alice ServBay'],
['$set' => ['age' => 31, 'status' => 'updated']]
);
printf("Matched %d document(s) for update, modified %d document(s).\n", $updateResult->getMatchedCount(), $updateResult->getModifiedCount());
// Query the updated document (optional)
$updatedDocument = $collection->findOne(['name' => 'Alice ServBay']);
echo "Updated document:\n";
if ($updatedDocument) {
print_r($updatedDocument);
}
// Delete a document (optional)
// $deleteResult = $collection->deleteOne(['name' => 'Alice ServBay']);
// printf("Deleted %d document(s).\n", $deleteResult->getDeletedCount());
} catch (\MongoDB\Driver\Exception\Exception $e) {
echo "An error occurred: " . $e->getMessage() . "\n";
} catch (\Exception $e) {
echo "An unexpected error occurred: " . $e->getMessage() . "\n";
}
echo "Script finished.\n";
?>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
Save this code as a PHP file, then run it in the terminal using ServBay’s PHP CLI, or access it via the web server configured in ServBay.
Notes and Best Practices
- MongoDB Service Status: Make sure the MongoDB package is set to "Running" in the ServBay GUI before connecting.
- Default Port: MongoDB runs on port
27017
by default. If your application needs to use a different port, specify it in the connection string. You can usually view or modify the port configuration in the ServBay GUI. - Extension vs. Driver: The PHP
mongodb.so
extension provides the underlying communication, while themongodb/mongodb
Composer package offers a higher-level, object-oriented API for database operations. Most modern PHP applications use the Composer package. - ServBay User CA/Public CA: ServBay supports using its built-in CA to issue SSL certificates. This helps simulate production HTTPS environments for local development. While local MongoDB connections typically don’t require SSL, you may need it for more advanced setups. ServBay also supports ACME protocol for requesting real certificates, as well as features such as data backup and database password reset—showcasing ServBay’s advantages as a comprehensive development environment.
- Database Management Tools: ServBay may not include a graphical management tool for MongoDB, but you can download the official MongoDB Compass or use CLI tools like
mongo
/mongosh
to manage your local MongoDB instance.
Frequently Asked Questions (FAQ)
Q: I enabled the PHP MongoDB extension, but my PHP script still can’t connect to MongoDB. What should I do?
A: Please make sure that you’ve started the MongoDB database service via the ServBay GUI. The PHP extension is just the interface—only the running database service provides the actual database instance. Also, check that the connection string is correct (usually mongodb://localhost:27017
).
Q: What’s the difference between the mongodb.so
extension and the mongodb/mongodb
Composer package?
A: mongodb.so
is the low-level PHP extension that provides communication between PHP and the MongoDB C driver (libmongoc). The mongodb/mongodb
Composer package is a higher-level PHP library built on top of this extension, offering easy-to-use, object-oriented APIs for CRUD operations, aggregation, and more. In modern PHP development, you typically need both the extension enabled and the Composer package installed.
Q: How do I change the MongoDB port or configuration?
A: You can view MongoDB package settings, including the port, in the ServBay GUI. For advanced configuration, edit the MongoDB config file, whose location can be found in the ServBay package details. After making changes, restart the MongoDB service.
Conclusion
ServBay offers PHP developers an extremely convenient MongoDB development environment. With its intuitive GUI, you can easily enable the PHP MongoDB extension and start the MongoDB database service. Combined with the official PHP driver installed via Composer, you can quickly set up a local PHP + MongoDB development environment—freeing you to focus on building your application logic. ServBay’s integrated features greatly simplify environment configuration, making local development and testing more efficient.