SlideShare une entreprise Scribd logo
1  sur  29
Pavel Gorbach
pavel.gorbach@volcanoideas.com
MongoDB & Drupal                                2/29



                      Plan
        1. MySQL as standard.
        2. Problems MySQL
        3. Reply by MongoDB. Structure
        4. Plus and Cons Mongo
        5. Mongo and Drupal. Let's be friends
        6. Work with users. Custom Module
        7. Aggregation Framework
MongoDB & Drupal                   3/29



               MySQL as standard
MongoDB & Drupal                                           4/29



               MySQL as standard

         1. It is a reliable product
         2. It is easy and convenient
         3. A description of 90% of all possible data
            storage structures *
         4. It is used by millions of people *


                                       * rough estimates
MongoDB & Drupal                            5/29



                   MySQL is SLOW


                         node_load – SLOW

                         user_load – SLOW

                         JOIN - SLOW
MongoDB & Drupal                             6/29



             MySQL - hard structuring


                        The choice between
                        a set of tables or
                        columns empty


                        1. Slow selection
                        2. Waste of memory
MongoDB & Drupal                 7/29



              Reply by MongoDB



   1. Very fast insert
   2. No joins => Fast select
   3. Power Update
MongoDB & Drupal                     8/29



                   Structure MySQL
MongoDB & Drupal                                            9/29



                   Structure Mongo
        {
            name: "Jhon",
            address:[
                {city: "Sevastopol", country: "Ukraine"},
                {city: "New York", country: "USA"}
            ],
            friends:[
                {id: 3}, {id: 13}
            ],
            email: "mail@urk.net",
            phone: "+380123456789"
        }
MongoDB & Drupal                 10/29



                    Mongo Plus

   1. Flexibility
   2. Scalability
   3. Atomicity
   4. Support for various
         types of data
   5. Object Query Language
   6. Map/Reduce
MongoDB & Drupal                   11/29



                   Mongo Minuses


   1. Enough young product
   2. Max object size - 4 Mb
   3. Max DB size - 2 GB
   4. Typing
   5. No transaction
MongoDB & Drupal                                      12/29



                   Mongo and PHP

                          Installing from a Pecl rep
                          OR
                          Download the library from
                          Githab and make



     Detailed documentation on PHP.net and living
     examples in the test folder inside the library
MongoDB & Drupal                  13/29


              Mongo and Drupal.
               Let's be friends
MongoDB & Drupal                                          14/29



                     Setting

   #MongoDB
   $conf['mongodb_connections'] = array(
     'default' => array( // Connection name/alias
         'host' => 'localhost', // Omit USER:PASS@
          'db' => 'drup_conf' // Database name.
      ),
  );
  $conf['field_storage_default'] = 'mongodb_field_storage';
MongoDB & Drupal             15/29



                   Modules
MongoDB & Drupal                                                         16/29



                                 Update
  function dc_mongodb_update($collection_name, $keys, $object,
          $upsert = TRUE) {

      // Select collection
      $collection = mongodb_collection($collection_name);

      if (!$collection || !$keys || !$object) {
        return FALSE;
      }

      $result = $collection->update($keys, $object, array('upsert' => $upsert));

      return $result;
  }
MongoDB & Drupal                                                           17/29



                                      Find
  function dc_mongodb_select($collection_name, $query = array(),
                       $fields = array(), $sort = array(), $limit = 0) {
     // Select collection
     $collection = mongodb_collection($collection_name);
     // Set query
     $mongo_result = $collection->find($query, $fields);
     $mongo_result->sort($sort);
     // Set limit if defined
     if ($limit > 0) {
        $mongo_result->limit($limit);
      }
      $result = array();
      while($item = $mongo_result->getNext()) {
        $result[] = $item;
      }
  return $result;
  }
MongoDB & Drupal                       18/29



                   Description task
      Each user can be:
      - name
      - surname
      - gender
      - post
      - any number of addresses
      - Friends List

      First and last name - required
      Another fields - optional
MongoDB & Drupal                                                           19/29



                          Structure - alone
  Users
  {                                     Address
      "uid" : 5,                        {
      "first_name" : "Jon",                 "uid" : 5,
      "last_name" : "Smit",                 "address" : [ {
      "gender " : "male",                      "country" : "USA",
      "post" : "manager",                      "city" : "New York",
  }                                            "address" : "st Jimmy street 4 "
                                               },
                                               {
  Friends                                         "country" : "Great Brithan",
  {                                               "city" : "London",
      "users" : [                                 "address" : "Queen palace"
         { "uid" : 1 }, { "uid" : 7 }          }]
       ]                                }
  }
MongoDB & Drupal                                             20/29



          The structure - all-inclusive
           Users
           {
             "uid" : 5,
             "first_name" : "Jon",
             "last_name" : "Smit",
             “gender" : "male",
             "post" : "manager",
             "address" : [ { "country" : "USA",   ...   }]
             "friends" : [ {
                 "first_name" : "Jon",
                 "last_name" : "Smit",
                 “gender " : "male",
                 "post" : "manager",
                 "address" : [ {     ... } ]
             }]
           }
MongoDB & Drupal                                            21/29



                    Structure - mixed
             {
                  "uid" : 5,
                  "profile" : {
                     "first_name" : "Jon",
                     "last_name" : "Smit",
                     "gender" : "male",
                     "post" : "manager",
                     "address" : [ {…}, {…} ]
                  },
                 "friends" : [
                          { "uid" : 1, "name" : "Bobby”},
                          { "uid" : 7, "name" : "Jynu“ }
                  ]
             }
MongoDB & Drupal                                                                 22/29



                      hook_user_update
 function dc_mongodb_user_user_update(&$edit, $account, $category)
 {
   $keys = array('uid' => (int) $account->uid);
   //Get user data from mongodb
   $data = dc_mongodb_select_one('users', $keys);
   $userOldName = $data['profile']['first_name'] ;
   //Set update data
   $data['uid'] = (int) $account->uid;
   $data['profile']['first_name'] = $edit['first_name'];
 //Update user collection
   dc_mongodb_update('users', $keys, $data);

     if ($userOldName != $edit['first_name']) {
          dc_mongodb_update('users', array('friends.uid' => $data['uid'] ),
             array('$set' => array('friends.$.name' => $edit['first_name'])), FALSE);
     }
 }
MongoDB & Drupal                                     23/29



            Aggregation Framework

       1. Means to calculate aggregated values
       without having to use map-reduce
       2. Provides similar functionality to GROUP
       BY and related SQL operators
       3. Add computed fields
       4. Create new virtual sub-objects
       5. Extract sub-fields into the top-level of
       results
MongoDB & Drupal                                              24/29



                       Aggregation wrapper
    /**
     * Mongo aggregate
     */
    function dc_mongodb_aggregate($collection_name, $opt) {
      // Select collection
      $collection = mongodb_collection($collection_name);

        if (!$collection) {
          return FALSE;
        }

        $result = $collection->aggregate($opt);
        unset($collection);

        return $result;
    }
MongoDB & Drupal                                                    25/29



                   Extract sub-fields

 $top_users = dc_mongodb_aggregate(         {
           „users‟,                               "uid" : 1,
  array(                                          "friend_name" : “Bob",
    array('$unwind' => '$friends'),               "frined_id" : 5
    array(                                  },
      '$project' => array(                  ...
        'uid' => 1,                         {
        '_id' => 0,                               "uid" : 1,
        'friend_uid' => '$friends.uid',           "friend_name" : “Alex",
        'friend_name' => '$friends.name',         "frined_id" : 12
    )                                       }
   ));
MongoDB & Drupal                                           26/29



                  Add virtual field
                                {
                                      "uid" : 1,
   array(                             "friend_name" : “Bob",
      '$project' => array(            "frined_id" : 5,
                                      "count " : 1
           ...
                                },
            'count' => array(   ...
               '$add' => 1      {
             )                        "uid" : 1,
        )                             "friend_name" : “Alex",
   )                                  "frined_id" : 12,
                                      "count" : 1
                                }
MongoDB & Drupal                                                   27/29



                                Group
 array(                                    {
                                             "_id " : {
    '$group' => array(
                                                "user_name " : “Bob",
      '_id' => array(                           "user_id " : 5
          'user_name' => '$friend_name',       },
          'user_id' => '$friend_uid',         "count " : 3
      ),                                   },
      'count' => array(                    ...
           '$sum' => '$count'              {
         )                                   "_id " : {
    )                                           "user_name " : “Alex",
                                                "user_id " : 2
 ),
                                               },
                                              "count " : 12
                                           }
MongoDB & Drupal                                                 28/29



                     Add sort and limit

   array(
       '$sort' => array(         {
            'count' => -1            "_id " : {
         )                              "user_name " : “Alex",
      ),                                "user_id " : 2
   array(                              },
       $limit' => 1                   "count " : 12
    )                            }
MongoDB & Drupal                           29/29



                   Questions ?


  Contact:
  E-mail: pavel.gorbach@volcanoideas.com
  Skype: rgnrok

Contenu connexe

Tendances

Building a Social Network with MongoDB
  Building a Social Network with MongoDB  Building a Social Network with MongoDB
Building a Social Network with MongoDB
Fred Chu
 
The Ruby/mongoDB ecosystem
The Ruby/mongoDB ecosystemThe Ruby/mongoDB ecosystem
The Ruby/mongoDB ecosystem
Harold Giménez
 
Meetup#1: 10 reasons to fall in love with MongoDB
Meetup#1: 10 reasons to fall in love with MongoDBMeetup#1: 10 reasons to fall in love with MongoDB
Meetup#1: 10 reasons to fall in love with MongoDB
Minsk MongoDB User Group
 
MongoDB Schema Design
MongoDB Schema DesignMongoDB Schema Design
MongoDB Schema Design
Alex Litvinok
 
Building web applications with mongo db presentation
Building web applications with mongo db presentationBuilding web applications with mongo db presentation
Building web applications with mongo db presentation
Murat Çakal
 
"Powerful Analysis with the Aggregation Pipeline (Tutorial)"
"Powerful Analysis with the Aggregation Pipeline (Tutorial)""Powerful Analysis with the Aggregation Pipeline (Tutorial)"
"Powerful Analysis with the Aggregation Pipeline (Tutorial)"
MongoDB
 

Tendances (19)

Building a Social Network with MongoDB
  Building a Social Network with MongoDB  Building a Social Network with MongoDB
Building a Social Network with MongoDB
 
MongoDB Schema Design
MongoDB Schema DesignMongoDB Schema Design
MongoDB Schema Design
 
Back to Basics Webinar 3: Schema Design Thinking in Documents
 Back to Basics Webinar 3: Schema Design Thinking in Documents Back to Basics Webinar 3: Schema Design Thinking in Documents
Back to Basics Webinar 3: Schema Design Thinking in Documents
 
Agile Schema Design: An introduction to MongoDB
Agile Schema Design: An introduction to MongoDBAgile Schema Design: An introduction to MongoDB
Agile Schema Design: An introduction to MongoDB
 
MongoDB Advanced Schema Design - Inboxes
MongoDB Advanced Schema Design - InboxesMongoDB Advanced Schema Design - Inboxes
MongoDB Advanced Schema Design - Inboxes
 
The Ruby/mongoDB ecosystem
The Ruby/mongoDB ecosystemThe Ruby/mongoDB ecosystem
The Ruby/mongoDB ecosystem
 
Meetup#1: 10 reasons to fall in love with MongoDB
Meetup#1: 10 reasons to fall in love with MongoDBMeetup#1: 10 reasons to fall in love with MongoDB
Meetup#1: 10 reasons to fall in love with MongoDB
 
MongoDB Europe 2016 - ETL for Pros – Getting Data Into MongoDB The Right Way
MongoDB Europe 2016 - ETL for Pros – Getting Data Into MongoDB The Right WayMongoDB Europe 2016 - ETL for Pros – Getting Data Into MongoDB The Right Way
MongoDB Europe 2016 - ETL for Pros – Getting Data Into MongoDB The Right Way
 
MongoDB Schema Design
MongoDB Schema DesignMongoDB Schema Design
MongoDB Schema Design
 
Webinar: Schema Design
Webinar: Schema DesignWebinar: Schema Design
Webinar: Schema Design
 
Webinar: General Technical Overview of MongoDB for Dev Teams
Webinar: General Technical Overview of MongoDB for Dev TeamsWebinar: General Technical Overview of MongoDB for Dev Teams
Webinar: General Technical Overview of MongoDB for Dev Teams
 
MongoDB Schema Design: Four Real-World Examples
MongoDB Schema Design: Four Real-World ExamplesMongoDB Schema Design: Four Real-World Examples
MongoDB Schema Design: Four Real-World Examples
 
Building a Scalable Inbox System with MongoDB and Java
Building a Scalable Inbox System with MongoDB and JavaBuilding a Scalable Inbox System with MongoDB and Java
Building a Scalable Inbox System with MongoDB and Java
 
Storing tree structures with MongoDB
Storing tree structures with MongoDBStoring tree structures with MongoDB
Storing tree structures with MongoDB
 
MongoDB Europe 2016 - Debugging MongoDB Performance
MongoDB Europe 2016 - Debugging MongoDB PerformanceMongoDB Europe 2016 - Debugging MongoDB Performance
MongoDB Europe 2016 - Debugging MongoDB Performance
 
Real World CouchDB
Real World CouchDBReal World CouchDB
Real World CouchDB
 
Building web applications with mongo db presentation
Building web applications with mongo db presentationBuilding web applications with mongo db presentation
Building web applications with mongo db presentation
 
"Powerful Analysis with the Aggregation Pipeline (Tutorial)"
"Powerful Analysis with the Aggregation Pipeline (Tutorial)""Powerful Analysis with the Aggregation Pipeline (Tutorial)"
"Powerful Analysis with the Aggregation Pipeline (Tutorial)"
 
Mongo db
Mongo dbMongo db
Mongo db
 

Similaire à MongoDB & Drupal

introtomongodb
introtomongodbintrotomongodb
introtomongodb
saikiran
 
MongoDB - A Document NoSQL Database
MongoDB - A Document NoSQL DatabaseMongoDB - A Document NoSQL Database
MongoDB - A Document NoSQL Database
Ruben Inoto Soto
 

Similaire à MongoDB & Drupal (20)

Build your first MongoDB App in Ruby @ StrangeLoop 2013
Build your first MongoDB App in Ruby @ StrangeLoop 2013Build your first MongoDB App in Ruby @ StrangeLoop 2013
Build your first MongoDB App in Ruby @ StrangeLoop 2013
 
MongoDB 101
MongoDB 101MongoDB 101
MongoDB 101
 
MongoDB a document store that won't let you down.
MongoDB a document store that won't let you down.MongoDB a document store that won't let you down.
MongoDB a document store that won't let you down.
 
introtomongodb
introtomongodbintrotomongodb
introtomongodb
 
Mongo-Drupal
Mongo-DrupalMongo-Drupal
Mongo-Drupal
 
MongoDB and DigitalOcean Automation with Cloud Manager
MongoDB and DigitalOcean Automation with Cloud ManagerMongoDB and DigitalOcean Automation with Cloud Manager
MongoDB and DigitalOcean Automation with Cloud Manager
 
Midgard2 - Content Repository for mobile applications
Midgard2 - Content Repository for mobile applicationsMidgard2 - Content Repository for mobile applications
Midgard2 - Content Repository for mobile applications
 
MongoDB
MongoDBMongoDB
MongoDB
 
Building your first app with MongoDB
Building your first app with MongoDBBuilding your first app with MongoDB
Building your first app with MongoDB
 
MongoDB, PHP and the cloud - php cloud summit 2011
MongoDB, PHP and the cloud - php cloud summit 2011MongoDB, PHP and the cloud - php cloud summit 2011
MongoDB, PHP and the cloud - php cloud summit 2011
 
MongoDB - A Document NoSQL Database
MongoDB - A Document NoSQL DatabaseMongoDB - A Document NoSQL Database
MongoDB - A Document NoSQL Database
 
Rails with mongodb
Rails with mongodbRails with mongodb
Rails with mongodb
 
This upload requires better support for ODP format
This upload requires better support for ODP formatThis upload requires better support for ODP format
This upload requires better support for ODP format
 
Spring Data MongoDB 介紹
Spring Data MongoDB 介紹Spring Data MongoDB 介紹
Spring Data MongoDB 介紹
 
MongoDB
MongoDBMongoDB
MongoDB
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
MongoDB
MongoDBMongoDB
MongoDB
 
Back to Basics Webinar 3 - Thinking in Documents
Back to Basics Webinar 3 - Thinking in DocumentsBack to Basics Webinar 3 - Thinking in Documents
Back to Basics Webinar 3 - Thinking in Documents
 
MongoDB Europe 2016 - Graph Operations with MongoDB
MongoDB Europe 2016 - Graph Operations with MongoDBMongoDB Europe 2016 - Graph Operations with MongoDB
MongoDB Europe 2016 - Graph Operations with MongoDB
 
Mongo learning series
Mongo learning series Mongo learning series
Mongo learning series
 

Dernier

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Dernier (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 

MongoDB & Drupal

  • 2. MongoDB & Drupal 2/29 Plan 1. MySQL as standard. 2. Problems MySQL 3. Reply by MongoDB. Structure 4. Plus and Cons Mongo 5. Mongo and Drupal. Let's be friends 6. Work with users. Custom Module 7. Aggregation Framework
  • 3. MongoDB & Drupal 3/29 MySQL as standard
  • 4. MongoDB & Drupal 4/29 MySQL as standard 1. It is a reliable product 2. It is easy and convenient 3. A description of 90% of all possible data storage structures * 4. It is used by millions of people * * rough estimates
  • 5. MongoDB & Drupal 5/29 MySQL is SLOW node_load – SLOW user_load – SLOW JOIN - SLOW
  • 6. MongoDB & Drupal 6/29 MySQL - hard structuring The choice between a set of tables or columns empty 1. Slow selection 2. Waste of memory
  • 7. MongoDB & Drupal 7/29 Reply by MongoDB 1. Very fast insert 2. No joins => Fast select 3. Power Update
  • 8. MongoDB & Drupal 8/29 Structure MySQL
  • 9. MongoDB & Drupal 9/29 Structure Mongo { name: "Jhon", address:[ {city: "Sevastopol", country: "Ukraine"}, {city: "New York", country: "USA"} ], friends:[ {id: 3}, {id: 13} ], email: "mail@urk.net", phone: "+380123456789" }
  • 10. MongoDB & Drupal 10/29 Mongo Plus 1. Flexibility 2. Scalability 3. Atomicity 4. Support for various types of data 5. Object Query Language 6. Map/Reduce
  • 11. MongoDB & Drupal 11/29 Mongo Minuses 1. Enough young product 2. Max object size - 4 Mb 3. Max DB size - 2 GB 4. Typing 5. No transaction
  • 12. MongoDB & Drupal 12/29 Mongo and PHP Installing from a Pecl rep OR Download the library from Githab and make Detailed documentation on PHP.net and living examples in the test folder inside the library
  • 13. MongoDB & Drupal 13/29 Mongo and Drupal. Let's be friends
  • 14. MongoDB & Drupal 14/29 Setting #MongoDB $conf['mongodb_connections'] = array( 'default' => array( // Connection name/alias 'host' => 'localhost', // Omit USER:PASS@ 'db' => 'drup_conf' // Database name. ), ); $conf['field_storage_default'] = 'mongodb_field_storage';
  • 15. MongoDB & Drupal 15/29 Modules
  • 16. MongoDB & Drupal 16/29 Update function dc_mongodb_update($collection_name, $keys, $object, $upsert = TRUE) { // Select collection $collection = mongodb_collection($collection_name); if (!$collection || !$keys || !$object) { return FALSE; } $result = $collection->update($keys, $object, array('upsert' => $upsert)); return $result; }
  • 17. MongoDB & Drupal 17/29 Find function dc_mongodb_select($collection_name, $query = array(), $fields = array(), $sort = array(), $limit = 0) { // Select collection $collection = mongodb_collection($collection_name); // Set query $mongo_result = $collection->find($query, $fields); $mongo_result->sort($sort); // Set limit if defined if ($limit > 0) { $mongo_result->limit($limit); } $result = array(); while($item = $mongo_result->getNext()) { $result[] = $item; } return $result; }
  • 18. MongoDB & Drupal 18/29 Description task Each user can be: - name - surname - gender - post - any number of addresses - Friends List First and last name - required Another fields - optional
  • 19. MongoDB & Drupal 19/29 Structure - alone Users { Address "uid" : 5, { "first_name" : "Jon", "uid" : 5, "last_name" : "Smit", "address" : [ { "gender " : "male", "country" : "USA", "post" : "manager", "city" : "New York", } "address" : "st Jimmy street 4 " }, { Friends "country" : "Great Brithan", { "city" : "London", "users" : [ "address" : "Queen palace" { "uid" : 1 }, { "uid" : 7 } }] ] } }
  • 20. MongoDB & Drupal 20/29 The structure - all-inclusive Users { "uid" : 5, "first_name" : "Jon", "last_name" : "Smit", “gender" : "male", "post" : "manager", "address" : [ { "country" : "USA", ... }] "friends" : [ { "first_name" : "Jon", "last_name" : "Smit", “gender " : "male", "post" : "manager", "address" : [ { ... } ] }] }
  • 21. MongoDB & Drupal 21/29 Structure - mixed { "uid" : 5, "profile" : { "first_name" : "Jon", "last_name" : "Smit", "gender" : "male", "post" : "manager", "address" : [ {…}, {…} ] }, "friends" : [ { "uid" : 1, "name" : "Bobby”}, { "uid" : 7, "name" : "Jynu“ } ] }
  • 22. MongoDB & Drupal 22/29 hook_user_update function dc_mongodb_user_user_update(&$edit, $account, $category) { $keys = array('uid' => (int) $account->uid); //Get user data from mongodb $data = dc_mongodb_select_one('users', $keys); $userOldName = $data['profile']['first_name'] ; //Set update data $data['uid'] = (int) $account->uid; $data['profile']['first_name'] = $edit['first_name']; //Update user collection dc_mongodb_update('users', $keys, $data); if ($userOldName != $edit['first_name']) { dc_mongodb_update('users', array('friends.uid' => $data['uid'] ), array('$set' => array('friends.$.name' => $edit['first_name'])), FALSE); } }
  • 23. MongoDB & Drupal 23/29 Aggregation Framework 1. Means to calculate aggregated values without having to use map-reduce 2. Provides similar functionality to GROUP BY and related SQL operators 3. Add computed fields 4. Create new virtual sub-objects 5. Extract sub-fields into the top-level of results
  • 24. MongoDB & Drupal 24/29 Aggregation wrapper /** * Mongo aggregate */ function dc_mongodb_aggregate($collection_name, $opt) { // Select collection $collection = mongodb_collection($collection_name); if (!$collection) { return FALSE; } $result = $collection->aggregate($opt); unset($collection); return $result; }
  • 25. MongoDB & Drupal 25/29 Extract sub-fields $top_users = dc_mongodb_aggregate( { „users‟, "uid" : 1, array( "friend_name" : “Bob", array('$unwind' => '$friends'), "frined_id" : 5 array( }, '$project' => array( ... 'uid' => 1, { '_id' => 0, "uid" : 1, 'friend_uid' => '$friends.uid', "friend_name" : “Alex", 'friend_name' => '$friends.name', "frined_id" : 12 ) } ));
  • 26. MongoDB & Drupal 26/29 Add virtual field { "uid" : 1, array( "friend_name" : “Bob", '$project' => array( "frined_id" : 5, "count " : 1 ... }, 'count' => array( ... '$add' => 1 { ) "uid" : 1, ) "friend_name" : “Alex", ) "frined_id" : 12, "count" : 1 }
  • 27. MongoDB & Drupal 27/29 Group array( { "_id " : { '$group' => array( "user_name " : “Bob", '_id' => array( "user_id " : 5 'user_name' => '$friend_name', }, 'user_id' => '$friend_uid', "count " : 3 ), }, 'count' => array( ... '$sum' => '$count' { ) "_id " : { ) "user_name " : “Alex", "user_id " : 2 ), }, "count " : 12 }
  • 28. MongoDB & Drupal 28/29 Add sort and limit array( '$sort' => array( { 'count' => -1 "_id " : { ) "user_name " : “Alex", ), "user_id " : 2 array( }, $limit' => 1 "count " : 12 ) }
  • 29. MongoDB & Drupal 29/29 Questions ? Contact: E-mail: pavel.gorbach@volcanoideas.com Skype: rgnrok