Skip to main content

MongoDB Drupal Integration: Improve scalability Part 1 - Bhimmu

MongoDB Drupal Integration: Improve scalability Part 1 - Bhimmu

Integration of Drupal with MongoDB to improve scalability

MongoDB Drupal Integration: NoSQL databases are versatile, scalable, and lightning-fast, learn the integration of Drupal with MongoDB to use the power of two open source champion!

MongoDB Drupal Integration 

Extensibility is one of the primary principle of Drupal that makes it first choice of content managers. In this article we will learn how to integrate MongoDB database into Drupal. 

What are the dependencies and the module configuration.

Using MongoDB contributed module we can prepare the MongoDB connection object. We need following settings to work with MongoDB Drupal Integration.

  • MongoDB 4.2 to 6.x server instance running locally or MongoDB Atlas Instance
  • The MongoDB php extension version 1.13 or later
  • Drupal 10 instance running on PHP 8.2
  • It is advised that you must install Drupal MongoDB module via composer dependency manager so that all the required libraries can be install along with the module.

In this blog we are going to connect MongoDB atlas instance, to show the MongoDB Drupal Integration, if you want to use locally hosted MongoDB instance you can do that as well.

MongoDB Atlas

we are going to use MongoDB free tier which can be availed after completing the sign up process. You can find the setup process on MongoDB's official YouTube channel.

 

Once you create a database in MongoDB atlas, go to the Database Services section and click on Connect link. 
 

Image
Connect Link

In the next screen you will see a section to choose your driver. We will choose PHP for this example.

Image
MongoDB Choose driver

 

After the above screen you will see option to copy the MongoDB atlas database connection string that we will use into Drupal 10.

 

Image
MongoDB connection string

Till here we have completed the MongoDB atlas database and got a connection string. Next we will download and install the MongoDB Drupal module.

composer require 'drupal/mongodb:^2.1' 

 Before enabling this module we will add the following settings to the bottom of your settings.php or settings.local.php file.

$configureMongoDb = function (array $settings): array {
  $settings['mongodb'] = [
    'clients' => [
      // Client alias => connection constructor parameters.
      'default' => [
        'uri' => 'CONNECTION_STRING_COPIED_FROM_MONGODB_ATLAS',
        'uriOptions' => [],
        'driverOptions' => [],
      ],
    ],
    'databases' => [
      'default' => ['default', 'YOUR_DATABASE_NAME'],
    ],
  ];

  return $settings;
};

// @codingStandardsIgnoreLine
$settings = $configureMongoDb($settings ?? []);

Make sure you have added the correct connection string containing the correct password in it. Next go and add some documents to your MongoDB atlas database.

How to test the MongoDB Drupal Integration

To test the connection we will create a controller and try to fetch some records from MongoDB collection.
 

<?php

namespace Drupal\bhimmu\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\mongodb\ClientFactory;
use Drupal\mongodb\DatabaseFactory;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Returns responses for Bhimmu routes.
 */
final class BhimmuController extends ControllerBase {

  /**
   * The controller constructor.
   */
  public function __construct(
    private readonly ClientFactory $mongodbClientFactory,
    private readonly DatabaseFactory $mongodbDatabaseFactory,
  ) {}

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container): self {
    return new self(
      $container->get('mongodb.client_factory'),
      $container->get('mongodb.database_factory'),
    );
  }

  /**
   * Builds the response.
   */
  public function __invoke(): array {
    // Make header row.
    $header = [
      'id' => $this->t('ID'),
      'title' => $this->t('Title'),
      'is_completed' => $this->t('Is Completed'),
      'remark' => $this->t('Remark'),
    ];

    // Invoke MongoDB instance.
    $database = $this->mongodbDatabaseFactory->get('default');

    // Fetch documents from a collection.
    /** @var \MongoDB\Model\BSONDocument $task */
    foreach ($database->Tasks->find() as $task) {
      $task = $task->jsonSerialize();
      $tasks[] = [
        'id' => [
          'data' => [
            '#markup' => $task->_id,
          ],
        ],
        'title' => [
          'data' => [
            '#markup' => $task->taskName,
          ],
        ],
        'is_completed' => [
          'data' => [
            '#markup' => $task->isComplete,
          ],
        ],
        'remark' => [
          'data' => [
            '#markup' => $task->remark,
          ],
        ],
      ];
    }

    $build['content'] = [
      '#theme' => 'table',
      '#header' => $header,
      '#rows' => $tasks,
      '#empty' => $this->t('There is no taks!'),
    ];

    return $build;
  }

}

We have created a controller at web/modules/bhimmu/src/Controller/BhimmuController.php

In this example we have created a Mongo collection with following columns.

taskName, isComplete, remark

Create a route which will invoke this controller.

bhimmu.mongo:
  path: '/bhimmu/mongo'
  defaults:
    _title: 'Mongo'
    _controller: '\Drupal\bhimmu\Controller\BhimmuController'
  requirements:
    _permission: 'access content'

Enable the mongo db and bhimmu module and clear the cache. Then you can visit to the url and if you have some records you will see them in the page. For example I am getting below results.

 

Image
MongoDB Result