{"id":55351,"date":"2022-08-03T15:15:29","date_gmt":"2022-08-03T09:45:29","guid":{"rendered":"https:\/\/www.tothenew.com\/blog\/?p=55351"},"modified":"2022-08-03T15:15:29","modified_gmt":"2022-08-03T09:45:29","slug":"how-to-integrate-mongodb-with-drupal","status":"publish","type":"post","link":"https:\/\/www.tothenew.com\/blog\/how-to-integrate-mongodb-with-drupal\/","title":{"rendered":"How to Integrate MongoDB with Drupal"},"content":{"rendered":"<p>In this tutorial we are going to learn how to integrate MongoDB with Drupal.<\/p>\n<p>Before proceeding we should know some of the following basics:<\/p>\n<h2><strong>What is MongoDB?\u00a0<\/strong><\/h2>\n<p>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.<\/p>\n<h2><strong>Install MongoDB on Linux?<\/strong><\/h2>\n<p>These documents provide instructions to install MongoDB Community Edition.<\/p>\n<p><a href=\"https:\/\/www.mongodb.com\/docs\/manual\/administration\/install-on-linux\/\">Install on Linux<\/a><br \/>\nInstall MongoDB Community Edition and required dependencies on Linux.<\/p>\n<p><a href=\"https:\/\/www.mongodb.com\/docs\/manual\/tutorial\/install-mongodb-on-os-x\/\">Install on MacOS<\/a><br \/>\nInstall MongoDB Community Edition on MacOS systems from MongoDB archives.<\/p>\n<p><a href=\"https:\/\/www.mongodb.com\/docs\/manual\/tutorial\/install-mongodb-on-windows\/\">Install on Windows<\/a><br \/>\nInstall MongoDB Community Edition on Windows systems and optionally start MongoDB as a Windows service.<\/p>\n<h2><strong>Install MongoDB PHP driver<\/strong><\/h2>\n<p>Please use below links install MongoDB PHP Driver<\/p>\n<ul class=\"child-menu-list\">\n<li class=\"current\"><a title=\"Installing the MongoDB PHP Driver with PECL\" href=\"https:\/\/www.php.net\/manual\/en\/mongodb.installation.pecl.php\">Installing the MongoDB PHP Driver with PECL<\/a><\/li>\n<li class=\"\"><a title=\"Installing the MongoDB PHP Driver on macOS with Homebrew\" href=\"https:\/\/www.php.net\/manual\/en\/mongodb.installation.homebrew.php\">Installing the MongoDB PHP Driver on macOS with Homebrew<\/a><\/li>\n<li class=\"\"><a title=\"Installing the MongoDB PHP Driver on Windows\" href=\"https:\/\/www.php.net\/manual\/en\/mongodb.installation.windows.php\">Installing the MongoDB PHP Driver on Windows<\/a><\/li>\n<li class=\"\"><a title=\"Building the MongoDB PHP Driver from source\" href=\"https:\/\/www.php.net\/manual\/en\/mongodb.installation.manual.php\">Building the MongoDB PHP Driver from source<\/a><\/li>\n<\/ul>\n<h2><strong>How to start\/stop\/restart\/status MongoDB service<\/strong><\/h2>\n<blockquote>\n<pre>sudo systemctl start mongod\r\nsudo systemctl status mongod\r\nsudo systemctl stop mongod\r\nsudo systemctl restart mongod<\/pre>\n<\/blockquote>\n<h2><strong>Install MongoDB module<\/strong><\/h2>\n<p><a href=\"https:\/\/www.drupal.org\/project\/mongodb\"><span style=\"font-weight: 400;\">https:\/\/www.drupal.org\/project\/mongodb<\/span><\/a><\/p>\n<p><span style=\"font-weight: 400;\">The <\/span><a href=\"http:\/\/www.mongodb.org\/\"><span style=\"font-weight: 400;\">MongoDB<\/span><\/a><span style=\"font-weight: 400;\"> module suite for Drupal 9\/8 stores data in MongoDB instead of the default Drupal SQL database.<\/span><\/p>\n<blockquote><p><span style=\"font-weight: 400;\">mongodb\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 | Drupal\/Drush wrapper around mongodb-php-library.<\/span><\/p>\n<p><span style=\"font-weight: 400;\">mongodb_storage\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 | Key-value storage in MongoDB.<\/span><\/p>\n<p><span style=\"font-weight: 400;\">mongodb_watchdog\u00a0 \u00a0 \u00a0 | Store logger (watchdog) messages in MongoDB.<\/span><\/p><\/blockquote>\n<h2><\/h2>\n<h2>Configure Drupal to use the MongoDB plugin<\/h2>\n<p>Once module is installed Than you need to put MongoDB connection in your settings.php or local.settings.php<\/p>\n<pre><strong>$settings['mongodb'] = [<\/strong>\r\n<strong>  'clients' =&gt; [<\/strong>\r\n<strong>      \/\/ Client alias =&gt; connection constructor parameters.<\/strong>\r\n<strong>      'default' =&gt; [<\/strong>\r\n<strong>      'uri' =&gt; 'mongodb:\/\/localhost:27017',<\/strong>\r\n<strong>      'uriOptions' =&gt; [],<\/strong>\r\n<strong>      'driverOptions' =&gt; [],<\/strong>\r\n<strong>    ],<\/strong>\r\n<strong>   ],<\/strong>\r\n<strong>  'databases' =&gt; [<\/strong>\r\n<strong>     \/\/ Database alias =&gt; [ client_alias, database_name ]<\/strong>\r\n<strong>    \/\/ 'default' =&gt; ['default', 'drupal'],<\/strong>\r\n<strong>    'keyvalue' =&gt; ['default', 'keyvalue'],\r\n<\/strong>    \/\/ logger is needed when you are using mongodb watchdog module.\r\n<strong>    'logger' =&gt; ['default', 'drupalmongo'],<\/strong>\r\n<strong>   ],<\/strong>\r\n<strong>];\r\n<\/strong>\r\n\r\nNow enable MongoDB Watchdog module and navigate to database log page. \r\nAll the list you will see here is populated from MongoDB.\r\n\r\n<\/pre>\n<h2>Simple Form to save input values in Mongo in Drupal.<\/h2>\n<p>I am expecting you have created custom module ttn_km and MongoDB configuration is done.<\/p>\n<p>In your simple form class file below code can used for Mongo operations.<\/p>\n<blockquote>\n<pre>&lt;?php\r\n\r\nnamespace Drupal\\ttn_km\\Form;\r\n\r\nuse Drupal\\Core\\Form\\FormBase;\r\nuse Drupal\\Core\\Form\\FormStateInterface;\r\nuse Symfony\\Component\\DependencyInjection\\ContainerInterface;\r\nuse Drupal\\mongodb\\MongoDb;\r\nuse Drupal\\Core\\Url;\r\nuse Drupal\\Core\\Link;\r\n\r\n\/**\r\n* Class MongodbOperationsForm.\r\n*\/\r\nclass MongodbOperationsForm extends FormBase {\r\n\r\n\/**\r\n* Drupal\\mongodb\\DatabaseFactory definition.\r\n*\r\n* @var \\Drupal\\mongodb\\DatabaseFactory\r\n*\/\r\nprotected $mongodbDatabaseFactory;\r\nprotected $messenger;\r\nprotected $current_request;\r\n\r\n\/**\r\n* {@inheritdoc}\r\n*\/\r\npublic static function create(ContainerInterface $container) {\r\n$instance = parent::create($container);\r\n$instance-&gt;mongodbDatabaseFactory = $container-&gt;get('mongodb.database_factory');\r\n$instance-&gt;messenger = $container-&gt;get('messenger');\r\n$instance-&gt;current_request = $container-&gt;get('request_stack');\r\nreturn $instance;\r\n}\r\n\r\n\/**\r\n* {@inheritdoc}\r\n*\/\r\npublic function getFormId() {\r\nreturn 'mongodb_operations_form';\r\n}\r\n\r\n\/**\r\n* {@inheritdoc}\r\n*\/\r\npublic function buildForm(array $form, FormStateInterface $form_state) {\r\n$id = $this-&gt;current_request-&gt;getCurrentRequest()-&gt;get(\"id\");\r\nif (!empty($id)) {\r\n\/\/ $this-&gt;getRowsById($id);\r\n}\r\n$form['first_name'] = [\r\n'#type' =&gt; 'textfield',\r\n'#title' =&gt; $this-&gt;t('First Name'),\r\n'#maxlength' =&gt; 64,\r\n'#size' =&gt; 64,\r\n'#weight' =&gt; '0',\r\n];\r\n$form['last_name'] = [\r\n'#type' =&gt; 'textfield',\r\n'#title' =&gt; $this-&gt;t('Last Name'),\r\n'#maxlength' =&gt; 64,\r\n'#size' =&gt; 64,\r\n'#weight' =&gt; '0',\r\n];\r\n$form['submit'] = [\r\n'#type' =&gt; 'submit',\r\n'#value' =&gt; $this-&gt;t('Save'),\r\n'#weight' =&gt; '0',\r\n];\r\n\r\n$form['rows'] = [\r\n'#theme' =&gt; 'table',\r\n'#header' =&gt; ['id', 'frist name', 'last name', 'link'],\r\n'#rows' =&gt; $this-&gt;getRowsFromMongo(),\r\n'#empty' =&gt;t('Your table is empty'),\r\n];\r\n$form['#cache'] = ['max-age' =&gt; 0];\r\nreturn $form;\r\n}\r\n\r\n\/**\r\n* {@inheritdoc}\r\n*\/\r\npublic function validateForm(array &amp;$form, FormStateInterface $form_state) {\r\nif (!empty($form_state-&gt;getValues()['first_name'])) {\r\n$database = $this-&gt;mongodbDatabaseFactory-&gt;get(\"logger\");\r\n$collection = $database-&gt;selectCollection('mongodb_operations_form');\r\n$rows = $collection-&gt;find(['first_name' =&gt; $form_state-&gt;getValues()['first_name']]);\r\nif (count($rows-&gt;toArray())) {\r\n$form_state-&gt;setErrorByName(\"first_name\", \"Fname Already exists\");\r\n}\r\n}\r\nparent::validateForm($form, $form_state);\r\n}\r\n\r\n\/**\r\n* {@inheritdoc}\r\n*\/\r\npublic function submitForm(array &amp;$form, FormStateInterface $form_state) {\r\nif (!empty($id)) {\r\n\/\/@todo update record with ID match.\r\n} else {\r\n$database = $this-&gt;mongodbDatabaseFactory-&gt;get(\"logger\");\r\n$collection = $database-&gt;selectCollection('mongodb_operations_form');\r\n$collection-&gt;insertOne([\r\n\"first_name\" =&gt; $form_state-&gt;getValue(\"first_name\"),\r\n\"last_name\" =&gt; $form_state-&gt;getValue(\"last_name\"),\r\n]);\r\n$this-&gt;messenger-&gt;addMessage(\"Mongo insertion done!!\");\r\n}\r\n\r\n}\r\n\r\nprotected function getRowsById($id = \"\") {\r\n$database = $this-&gt;mongodbDatabaseFactory-&gt;get(\"logger\");\r\n$collection = $database-&gt;selectCollection('mongodb_operations_form');\r\n$rows = $collection-&gt;findOne([\"_id\" =&gt; new \\MongoDB\\BSON\\ObjectID($id)]);\r\ndump($rows-&gt;toArray());\r\ndie;\r\n}\r\n\r\n\r\npublic function getRowsFromMongo() {\r\n$database = $this-&gt;mongodbDatabaseFactory-&gt;get(\"logger\");\r\n$collection = $database-&gt;selectCollection('mongodb_operations_form');\r\n$rows = $collection-&gt;find();\r\n$tableRows = [];\r\nforeach( $rows as $row) {\r\n$url = Url::fromRoute('ttn_km.mongodb_operations_form', array('id' =&gt; (string)$row-&gt;_id));\r\n$project_link = Link::fromTextAndUrl(t('Edit'), $url);\r\n\r\n$tableRows[] = [\r\n'id' =&gt; (string)$row-&gt;_id,\r\n'fname' =&gt; $row-&gt;first_name,\r\n'lname' =&gt; $row-&gt;last_name,\r\n'link' =&gt; $project_link-&gt;toString(),\r\n];\r\n}\r\nreturn $tableRows;\r\n}\r\n\r\n}<\/pre>\n<\/blockquote>\n<pre><\/pre>\n<div class=\"ap-custom-wrapper\"><\/div><!--ap-custom-wrapper-->","protected":false},"excerpt":{"rendered":"<p>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?\u00a0 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 [&hellip;]<\/p>\n","protected":false},"author":1368,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":134},"categories":[3602],"tags":[4862],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/55351"}],"collection":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/users\/1368"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/comments?post=55351"}],"version-history":[{"count":2,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/55351\/revisions"}],"predecessor-version":[{"id":55356,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/55351\/revisions\/55356"}],"wp:attachment":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/media?parent=55351"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/categories?post=55351"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/tags?post=55351"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}