How to Integrate MongoDB with Drupal

03 / Aug / 2022 by Rajveer Singh 0 comments

In this tutorial we are going to learn how to integrate MongoDB with Drupal.

Before proceeding we should know some of the following basics:

What is MongoDB? 

MongoDB is a source-available cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with optional schemas. MongoDB is developed by MongoDB Inc. and licensed under the Server Side Public License which is deemed non-free by several distributions.

Install MongoDB on Linux?

These documents provide instructions to install MongoDB Community Edition.

Install on Linux
Install MongoDB Community Edition and required dependencies on Linux.

Install on MacOS
Install MongoDB Community Edition on MacOS systems from MongoDB archives.

Install on Windows
Install MongoDB Community Edition on Windows systems and optionally start MongoDB as a Windows service.

Install MongoDB PHP driver

Please use below links install MongoDB PHP Driver

How to start/stop/restart/status MongoDB service

sudo systemctl start mongod
sudo systemctl status mongod
sudo systemctl stop mongod
sudo systemctl restart mongod

Install MongoDB module

https://www.drupal.org/project/mongodb

The MongoDB module suite for Drupal 9/8 stores data in MongoDB instead of the default Drupal SQL database.

mongodb                        | Drupal/Drush wrapper around mongodb-php-library.

mongodb_storage          | Key-value storage in MongoDB.

mongodb_watchdog      | Store logger (watchdog) messages in MongoDB.

Configure Drupal to use the MongoDB plugin

Once module is installed Than you need to put MongoDB connection in your settings.php or local.settings.php

$settings['mongodb'] = [
  'clients' => [
      // Client alias => connection constructor parameters.
      'default' => [
      'uri' => 'mongodb://localhost:27017',
      'uriOptions' => [],
      'driverOptions' => [],
    ],
   ],
  'databases' => [
     // Database alias => [ client_alias, database_name ]
    // 'default' => ['default', 'drupal'],
    'keyvalue' => ['default', 'keyvalue'],
    // logger is needed when you are using mongodb watchdog module.
    'logger' => ['default', 'drupalmongo'],
   ],
];


Now enable MongoDB Watchdog module and navigate to database log page. 
All the list you will see here is populated from MongoDB.

Simple Form to save input values in Mongo in Drupal.

I am expecting you have created custom module ttn_km and MongoDB configuration is done.

In your simple form class file below code can used for Mongo operations.

<?php

namespace Drupal\ttn_km\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\mongodb\MongoDb;
use Drupal\Core\Url;
use Drupal\Core\Link;

/**
* Class MongodbOperationsForm.
*/
class MongodbOperationsForm extends FormBase {

/**
* Drupal\mongodb\DatabaseFactory definition.
*
* @var \Drupal\mongodb\DatabaseFactory
*/
protected $mongodbDatabaseFactory;
protected $messenger;
protected $current_request;

/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
$instance = parent::create($container);
$instance->mongodbDatabaseFactory = $container->get('mongodb.database_factory');
$instance->messenger = $container->get('messenger');
$instance->current_request = $container->get('request_stack');
return $instance;
}

/**
* {@inheritdoc}
*/
public function getFormId() {
return 'mongodb_operations_form';
}

/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$id = $this->current_request->getCurrentRequest()->get("id");
if (!empty($id)) {
// $this->getRowsById($id);
}
$form['first_name'] = [
'#type' => 'textfield',
'#title' => $this->t('First Name'),
'#maxlength' => 64,
'#size' => 64,
'#weight' => '0',
];
$form['last_name'] = [
'#type' => 'textfield',
'#title' => $this->t('Last Name'),
'#maxlength' => 64,
'#size' => 64,
'#weight' => '0',
];
$form['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Save'),
'#weight' => '0',
];

$form['rows'] = [
'#theme' => 'table',
'#header' => ['id', 'frist name', 'last name', 'link'],
'#rows' => $this->getRowsFromMongo(),
'#empty' =>t('Your table is empty'),
];
$form['#cache'] = ['max-age' => 0];
return $form;
}

/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
if (!empty($form_state->getValues()['first_name'])) {
$database = $this->mongodbDatabaseFactory->get("logger");
$collection = $database->selectCollection('mongodb_operations_form');
$rows = $collection->find(['first_name' => $form_state->getValues()['first_name']]);
if (count($rows->toArray())) {
$form_state->setErrorByName("first_name", "Fname Already exists");
}
}
parent::validateForm($form, $form_state);
}

/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
if (!empty($id)) {
//@todo update record with ID match.
} else {
$database = $this->mongodbDatabaseFactory->get("logger");
$collection = $database->selectCollection('mongodb_operations_form');
$collection->insertOne([
"first_name" => $form_state->getValue("first_name"),
"last_name" => $form_state->getValue("last_name"),
]);
$this->messenger->addMessage("Mongo insertion done!!");
}

}

protected function getRowsById($id = "") {
$database = $this->mongodbDatabaseFactory->get("logger");
$collection = $database->selectCollection('mongodb_operations_form');
$rows = $collection->findOne(["_id" => new \MongoDB\BSON\ObjectID($id)]);
dump($rows->toArray());
die;
}


public function getRowsFromMongo() {
$database = $this->mongodbDatabaseFactory->get("logger");
$collection = $database->selectCollection('mongodb_operations_form');
$rows = $collection->find();
$tableRows = [];
foreach( $rows as $row) {
$url = Url::fromRoute('ttn_km.mongodb_operations_form', array('id' => (string)$row->_id));
$project_link = Link::fromTextAndUrl(t('Edit'), $url);

$tableRows[] = [
'id' => (string)$row->_id,
'fname' => $row->first_name,
'lname' => $row->last_name,
'link' => $project_link->toString(),
];
}
return $tableRows;
}

}

FOUND THIS USEFUL? SHARE IT

Tag -

Drupal

Leave a Reply

Your email address will not be published. Required fields are marked *