OOP 2013:
Praktische Einführung in MongoDB
tobias.trelle@codecentric.de
@tobiastrelle

 codecentric AG                1
Tobias Trelle

                 -   Senior IT Consultant codecentric AG

                 -   MongoDB User-Gruppe Düsseldorf

                 -   MongoDB-Buch

codecentric AG        2
„It‘s not my fault the chapters are
short, MongoDB is just easy to learn“

      aus „The Little MongoDB book“




codecentric AG              3
MongoDB?

                 „humongous“ = gigantisch,
                      wahnsinnig groß

                  http://www.mongodb.org
codecentric AG           4
MongoDB?


      NoSQL-Datenbank

      Dokumenten-orientiert

      Hochperformant, horizontal skalierbar (scale-out)

      Replication & Sharding out-of-the-box

      Map/Reduce

      Geospatial Indexes / Queries
codecentric AG                  5
Grundkonzept MongoDB-Server


                               Server

Relationales
                              Database
Pendant                                    Aber …
                                           Flexibles
            Tabelle           Collection
                                           Schema

                 Zeile        Document


                                            - Arrays
                 Spalte         Field
                                            - Rekursiv
codecentric AG            6
Document

{
      title: „Praxisbuch Mongo“,
      version: 0.1,
      copies_sold: 0,
      authors: [
         { name: „Uwe Seiler“,
           email: „uwe.seiler@codecentric.de“ },
         { name: „Tobias Trelle“,
           email: „tobias.trelle@codecentric.de“}
      ]
}
codecentric AG        7
Document


      Document = Geordnete Menge von Key/Value-Paaren

      Key = UTF-8-String

      Value = Einfacher Datentyp | Array[Value] | Document

      Einfacher Datentyp = String
           | Integer32
           | Integer64
           | Double
           | Timestamp
           …
codecentric AG                 8
BSON-Format


      Dokumente werden im BSON-Format verwaltet und gespeichert

      http://bsonspec.org/#/specification

      BSON = Binary JSON (!= JSON)

      Teilweise größer als JSON, aber besser traversierbar

      Keys stehen in jedem Dokument --> kurz fassen!




codecentric AG                  9
BSON Beispiel


{ hello: "MongoDB" }

x18x00x00x00
   x02
       hellox00
       x08x00x00x00MongoDBx00
x00

codecentric AG   10
Live Session


      CRUD Operations           Replication

      Queries                   Sharding

      Geospatial Queries        MongoDB Java Driver &
                                Spring Data MongoDB
      Map/Reduce




codecentric AG             11
CRUD = IFUR


                 insert(…)

                 find(…), findOne(…)

                 update(…)

                 remove()
codecentric AG               12
Geospatial Queries

      Index auf 2-dimensionalen
      Koordinaten

      _id: "A", position: [0.001, -0.002]
      _id: "B", position: [0.75, 0.75]
      _id: "C", position: [0.5, 0.5]
      _id: "D", position: [-0.5, -0.5]

      Queries basieren auf Abständen
      und Shapes

      Details:
      http://blog.codecentric.de/en/2012/02/spring-data-mongodb-geospatial-queries/


codecentric AG                         13
Map/Reduce


      Algorithmus/Framework für Berechnungen auf
      Datenmengen basierend auf zwei Phasen:

      Map & Reduce

      Die Map-Phase kann nebenläufig und verteilt (im Cluster)
      auf großen Datenmengen (Petabytes) ausgeführt werden

 Apache Hadoop


codecentric AG             14
Map/Reduce mit MongoDB


      Wird auf einer Untermenge / allen Dokumenten einer
      Collection ausgeführt

      Map / Reduce-Funktionen sind in JavaScript implementiert

      Ergebnisse sind Dokumente in einer Ziel-Collection




codecentric AG             15
Map/Reduce Beispiel
                                                                           Map output:
      Aufgabe: Vorkommen von Tags zählen:                                  key = „cc“, value = 1
                                                                           key = „mongodb“, value = 1
                 {name: „Doc 1“, tags: [ „cc“, „mongodb“, „nosql“ ] }      key = „nosql“, value = 1
                 {name: „Doc 2“, tags: [ „cc“, „agile“ ] }
                 {name: „Doc 3“, tags: [ „cc“, „nosql“ ] }                 key = „cc“, value = 1
                                                                           key = „agile“, value = 1
      map = function() { this.tags.forEach( function(tag) {                key = „cc“, value = 1
           emit( tag, 1 );                                                 key = „nosql“, value = 1
           })
      }
      reduce = function(key, values) {
           return values.length;                                        Reduce input:
      }                                                                 key = „cc“, values = [ 1, 1, 1 ]
                                                                        key = „mongodb“, values = [ 1 ]
                                                                        key = „nosql“, values = [ 1,1 ]
                                                                        key = „agile“, values = [ 1 ]


codecentric AG                                 16
Aggregation Framework


      Seit Version 2.2

      Alternative zu Map/Reduce

      db.docs.aggregate(
          {$project:{_id:0,tags:1}},
          {$unwind: "$tags"},
          {$group:{_id:"$tags", n:{$sum:1}}}
      )


codecentric AG              17
MongoDB Replikation: Replica Sets

      Grundprinzip: Master/Slave + Election

      Writes nur auf den Master, Reads ggfs. auch von Slaves

      Slaves wählen automatisch neuen Master bei Ausfall


                                          Replica Set, n = 3

                                                          Secondary 1
                 Client         Primary
                                                          Secondary 2

codecentric AG             18
MongoDB Sharding

      Fragmentierung der Daten auf n Sharding-Knoten,
      jedes Dokument wird einmal persistiert

      Config Server = Buchhalter für Meta-Daten

      Switch: Gateway
                                           Sharding Setup
      für die Clients
                                  Config                    Shard 1
                                  Server


                    Client        Switch                    Shard 2

codecentric AG               19
MongoDB Produktion: Sharding + Replica Sets

                     Node 1                Node 2           Node 3

                    <<Config>>             <<Config>>      <<Config>>
                   mongod                 mongod          mongod


                   <<Primary>>           <<Secondary>>   << Secondary >>
      Shard 1      mongod                 mongod          mongod


                  << Secondary >>         <<Primary>>    << Secondary >>
      Shard 2      mongod                 mongod          mongod


                   <<Switch>>             <<Switch>>      <<Switch>>
                  mongos                  mongos          mongos

                 App Server              App Server      App Server

codecentric AG                      20
MongoDB Sharding Beispiel: Initialer Zustand
mongos> sh.status()
--- Sharding Status ---
   sharding version: { "_id" : 1, "version" : 3 }
   shards:                                                                      2 Shards
             {   "_id" : "shard0000",     "host" : "tmp-pc:9000" }
             {   "_id" : "shard0001",     "host" : "tmp-pc:9001" }
   databases:
             {   "_id" : "admin",   "partitioned" : false,      "primary" : "config" }
             {   "_id" : "data",    "partitioned" : true,      "primary" : "shard0000" }
                      data.foo chunks:
                                         shard0000         1
                              { "age" : { $minKey : 1 } } -->> { "age" : { $maxKey : 1 } } on : shard0000 { "t" : 1000,
     "i" : 0 }




codecentric AG                                        21
MongoDB Sharding Beispiel: Chunks verteilen sich
mongos> sh.status()
--- Sharding Status ---
   sharding version: { "_id" : 1, "version" : 3 }
   shards:                                                                      2 Shards
             {   "_id" : "shard0000",     "host" : "tmp-pc:9000" }
             {   "_id" : "shard0001",     "host" : "tmp-pc:9001" }
   databases:
             {   "_id" : "admin",   "partitioned" : false,      "primary" : "config" }
             {   "_id" : "data",    "partitioned" : true,      "primary" : "shard0000" }
                      data.foo chunks:
                                         shard0001         4
                                         shard0000         5
              Chunks
                              { "age" : { $minKey : 1 } } -->> { "age" : 50 } on : shard0001 { "t" : 2000, "i" : 0 }
            are equally
            distributed       { "age" : 50 } -->> { "age" : 53 } on : shard0001 { "t" : 3000, "i" : 0 }
                              { "age" : 53 } -->> { "age" : 54 } on : shard0001 { "t" : 4000, "i" : 0 }
                              { "age" : 54 } -->> { "age" : 58 } on : shard0001 { "t" : 5000, "i" : 0 }
                              { "age" : 58 } -->> { "age" : 60 } on : shard0000 { "t" : 5000, "i" : 1 }
                              { "age" : 60 } -->> { "age" : 63 } on : shard0000 { "t" : 1000, "i" : 14 }
                              { "age" : 63 } -->> { "age" : 65 } on : shard0000 { "t" : 1000, "i" : 11 }
                              { "age" : 65 } -->> { "age" : 69 } on : shard0000 { "t" : 1000, "i" : 12 }
                              { "age" : 69 } -->> { "age" : { $maxKey : 1 } } on : shard0000 { "t" : 1000, "i" : 4 }


codecentric AG                                        22
MongoDB Treiber


        Ein Wire-Protokoll für alle Client-Sprachen

        Pro Sprache ein Treiber

      Übersicht:
      http://www.mongodb.org/display/DOCS/Drivers




codecentric AG             23
MongoDB Treiber


Beispiele
 Sprache            Struktur
 JavaScript, Python {“hello": “MongoDB" }
 Ruby, Perl         {“hello" => “MongoDB" }
 C++                BSONObj p = BSON(“hello" << “MongoDB");
 Java               DBObject obj = new BasicDBObject();
                    obj.put(“hello", “MongoDB");




codecentric AG                 24
MongoDB Treibers


Wesentliche Aufgaben eines Treibers

      Konvertierung der sprachabh. Datenstrukturen 
       BSON-Format

        Generierung der _id-Werte

      Treiber macht möglichst viel, um Server zu
      entlasten
codecentric AG           25
MongoDB Java-Treiber


      Einzelnes JAR ohne weitere Abhängigkeiten

      <dependency>
         <groupId>org.mongodb</groupId>
         <artifactId>mongo-java-driver</artifactId>
         <version>2.10.0</version>
      </dependency>



      github: https://github.com/mongodb/mongo-java-driver



codecentric AG                 26
Spring Data MongoDB
                                              Spring Data
                                  CrudRepository     PagingAndSortingRepository

                  Spring Data      Spring Data          Spring Data           Spring Data
                      JPA           MongoDB               Neo4j                    …
                 JpaRepository   MongoRepository      GraphRepository
                                 MongoTemplate         Neo4jTemplate


                                                      Embedded      REST


                      JPA        Mongo Java Driver

                     JDBC



                    RDBMS             MongoDB               Neo4j                  …




codecentric AG                           27
Spring Data MongoDB

Template
     Abstraktion vom MongoDB Java Driver
     Konfiguration von mongod / mongos-Instanzen und Collections
     Verwaltung von Collections
     Map/Reduce-Aufrufe

Object Mapping
     Annotationen @Document, @Field, @Index etc.
     Klassen werden auf Collections abgebildet, Java-Objekte auf Dokumente

Repository Support
     Schlüsselwörter werden auf Query-Operatoren abgebildet
     Geospatial Queries

codecentric AG                 28
MongoDB User-Gruppen (MUGs)

MongoDB User-Gruppe Düsseldorf           MongoDB User-Gruppe Berlin
https://www.xing.com/net/mongodb-dus     http://www.meetup.com/MUGBerlin/
@MongoDUS                                @MUGBerlin


MongoDB User-Gruppe Frankfurt/Main       Hamburg MongoDB User Group
https://www.xing.com/net/mongodb-ffm     https://www.xing.com/net/mugh
@MongoFFM


MongoDB User-Gruppe München
http://www.meetup.com/Muenchen-MongoDB-User-Group/
@mongomuc




codecentric AG                     29
QUESTION?

Tobias Trelle

codecentric AG
Merscheider Str. 1
42699 Solingen

tel              +49 (0) 212.233628.47
fax              +49 (0) 212.233628.79
mail             Tobias.Trelle@codecentric.de
twitter          @tobiastrelle




www.codecentric.de
blog.codecentric.de/en/author/tobias-trelle
www.xing.com/net/mongodb-dus

codecentric AG                              30

OOP 2013: Praktische Einführung in MongoDB

  • 1.
    OOP 2013: Praktische Einführungin MongoDB tobias.trelle@codecentric.de @tobiastrelle codecentric AG 1
  • 2.
    Tobias Trelle - Senior IT Consultant codecentric AG - MongoDB User-Gruppe Düsseldorf - MongoDB-Buch codecentric AG 2
  • 3.
    „It‘s not myfault the chapters are short, MongoDB is just easy to learn“ aus „The Little MongoDB book“ codecentric AG 3
  • 4.
    MongoDB? „humongous“ = gigantisch, wahnsinnig groß http://www.mongodb.org codecentric AG 4
  • 5.
    MongoDB? NoSQL-Datenbank Dokumenten-orientiert Hochperformant, horizontal skalierbar (scale-out) Replication & Sharding out-of-the-box Map/Reduce Geospatial Indexes / Queries codecentric AG 5
  • 6.
    Grundkonzept MongoDB-Server Server Relationales Database Pendant Aber … Flexibles Tabelle Collection Schema Zeile Document - Arrays Spalte Field - Rekursiv codecentric AG 6
  • 7.
    Document { title: „Praxisbuch Mongo“, version: 0.1, copies_sold: 0, authors: [ { name: „Uwe Seiler“, email: „uwe.seiler@codecentric.de“ }, { name: „Tobias Trelle“, email: „tobias.trelle@codecentric.de“} ] } codecentric AG 7
  • 8.
    Document Document = Geordnete Menge von Key/Value-Paaren Key = UTF-8-String Value = Einfacher Datentyp | Array[Value] | Document Einfacher Datentyp = String | Integer32 | Integer64 | Double | Timestamp … codecentric AG 8
  • 9.
    BSON-Format Dokumente werden im BSON-Format verwaltet und gespeichert http://bsonspec.org/#/specification BSON = Binary JSON (!= JSON) Teilweise größer als JSON, aber besser traversierbar Keys stehen in jedem Dokument --> kurz fassen! codecentric AG 9
  • 10.
    BSON Beispiel { hello:"MongoDB" } x18x00x00x00 x02 hellox00 x08x00x00x00MongoDBx00 x00 codecentric AG 10
  • 11.
    Live Session CRUD Operations Replication Queries Sharding Geospatial Queries MongoDB Java Driver & Spring Data MongoDB Map/Reduce codecentric AG 11
  • 12.
    CRUD = IFUR insert(…) find(…), findOne(…) update(…) remove() codecentric AG 12
  • 13.
    Geospatial Queries Index auf 2-dimensionalen Koordinaten _id: "A", position: [0.001, -0.002] _id: "B", position: [0.75, 0.75] _id: "C", position: [0.5, 0.5] _id: "D", position: [-0.5, -0.5] Queries basieren auf Abständen und Shapes Details: http://blog.codecentric.de/en/2012/02/spring-data-mongodb-geospatial-queries/ codecentric AG 13
  • 14.
    Map/Reduce Algorithmus/Framework für Berechnungen auf Datenmengen basierend auf zwei Phasen: Map & Reduce Die Map-Phase kann nebenläufig und verteilt (im Cluster) auf großen Datenmengen (Petabytes) ausgeführt werden  Apache Hadoop codecentric AG 14
  • 15.
    Map/Reduce mit MongoDB Wird auf einer Untermenge / allen Dokumenten einer Collection ausgeführt Map / Reduce-Funktionen sind in JavaScript implementiert Ergebnisse sind Dokumente in einer Ziel-Collection codecentric AG 15
  • 16.
    Map/Reduce Beispiel Map output: Aufgabe: Vorkommen von Tags zählen: key = „cc“, value = 1 key = „mongodb“, value = 1 {name: „Doc 1“, tags: [ „cc“, „mongodb“, „nosql“ ] } key = „nosql“, value = 1 {name: „Doc 2“, tags: [ „cc“, „agile“ ] } {name: „Doc 3“, tags: [ „cc“, „nosql“ ] } key = „cc“, value = 1 key = „agile“, value = 1 map = function() { this.tags.forEach( function(tag) { key = „cc“, value = 1 emit( tag, 1 ); key = „nosql“, value = 1 }) } reduce = function(key, values) { return values.length; Reduce input: } key = „cc“, values = [ 1, 1, 1 ] key = „mongodb“, values = [ 1 ] key = „nosql“, values = [ 1,1 ] key = „agile“, values = [ 1 ] codecentric AG 16
  • 17.
    Aggregation Framework Seit Version 2.2 Alternative zu Map/Reduce db.docs.aggregate( {$project:{_id:0,tags:1}}, {$unwind: "$tags"}, {$group:{_id:"$tags", n:{$sum:1}}} ) codecentric AG 17
  • 18.
    MongoDB Replikation: ReplicaSets Grundprinzip: Master/Slave + Election Writes nur auf den Master, Reads ggfs. auch von Slaves Slaves wählen automatisch neuen Master bei Ausfall Replica Set, n = 3 Secondary 1 Client Primary Secondary 2 codecentric AG 18
  • 19.
    MongoDB Sharding Fragmentierung der Daten auf n Sharding-Knoten, jedes Dokument wird einmal persistiert Config Server = Buchhalter für Meta-Daten Switch: Gateway Sharding Setup für die Clients Config Shard 1 Server Client Switch Shard 2 codecentric AG 19
  • 20.
    MongoDB Produktion: Sharding+ Replica Sets Node 1 Node 2 Node 3 <<Config>> <<Config>> <<Config>> mongod mongod mongod <<Primary>> <<Secondary>> << Secondary >> Shard 1 mongod mongod mongod << Secondary >> <<Primary>> << Secondary >> Shard 2 mongod mongod mongod <<Switch>> <<Switch>> <<Switch>> mongos mongos mongos App Server App Server App Server codecentric AG 20
  • 21.
    MongoDB Sharding Beispiel:Initialer Zustand mongos> sh.status() --- Sharding Status --- sharding version: { "_id" : 1, "version" : 3 } shards: 2 Shards { "_id" : "shard0000", "host" : "tmp-pc:9000" } { "_id" : "shard0001", "host" : "tmp-pc:9001" } databases: { "_id" : "admin", "partitioned" : false, "primary" : "config" } { "_id" : "data", "partitioned" : true, "primary" : "shard0000" } data.foo chunks: shard0000 1 { "age" : { $minKey : 1 } } -->> { "age" : { $maxKey : 1 } } on : shard0000 { "t" : 1000, "i" : 0 } codecentric AG 21
  • 22.
    MongoDB Sharding Beispiel:Chunks verteilen sich mongos> sh.status() --- Sharding Status --- sharding version: { "_id" : 1, "version" : 3 } shards: 2 Shards { "_id" : "shard0000", "host" : "tmp-pc:9000" } { "_id" : "shard0001", "host" : "tmp-pc:9001" } databases: { "_id" : "admin", "partitioned" : false, "primary" : "config" } { "_id" : "data", "partitioned" : true, "primary" : "shard0000" } data.foo chunks: shard0001 4 shard0000 5 Chunks { "age" : { $minKey : 1 } } -->> { "age" : 50 } on : shard0001 { "t" : 2000, "i" : 0 } are equally distributed { "age" : 50 } -->> { "age" : 53 } on : shard0001 { "t" : 3000, "i" : 0 } { "age" : 53 } -->> { "age" : 54 } on : shard0001 { "t" : 4000, "i" : 0 } { "age" : 54 } -->> { "age" : 58 } on : shard0001 { "t" : 5000, "i" : 0 } { "age" : 58 } -->> { "age" : 60 } on : shard0000 { "t" : 5000, "i" : 1 } { "age" : 60 } -->> { "age" : 63 } on : shard0000 { "t" : 1000, "i" : 14 } { "age" : 63 } -->> { "age" : 65 } on : shard0000 { "t" : 1000, "i" : 11 } { "age" : 65 } -->> { "age" : 69 } on : shard0000 { "t" : 1000, "i" : 12 } { "age" : 69 } -->> { "age" : { $maxKey : 1 } } on : shard0000 { "t" : 1000, "i" : 4 } codecentric AG 22
  • 23.
    MongoDB Treiber Ein Wire-Protokoll für alle Client-Sprachen Pro Sprache ein Treiber Übersicht: http://www.mongodb.org/display/DOCS/Drivers codecentric AG 23
  • 24.
    MongoDB Treiber Beispiele Sprache Struktur JavaScript, Python {“hello": “MongoDB" } Ruby, Perl {“hello" => “MongoDB" } C++ BSONObj p = BSON(“hello" << “MongoDB"); Java DBObject obj = new BasicDBObject(); obj.put(“hello", “MongoDB"); codecentric AG 24
  • 25.
    MongoDB Treibers Wesentliche Aufgabeneines Treibers Konvertierung der sprachabh. Datenstrukturen   BSON-Format Generierung der _id-Werte Treiber macht möglichst viel, um Server zu entlasten codecentric AG 25
  • 26.
    MongoDB Java-Treiber Einzelnes JAR ohne weitere Abhängigkeiten <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>2.10.0</version> </dependency> github: https://github.com/mongodb/mongo-java-driver codecentric AG 26
  • 27.
    Spring Data MongoDB Spring Data CrudRepository PagingAndSortingRepository Spring Data Spring Data Spring Data Spring Data JPA MongoDB Neo4j … JpaRepository MongoRepository GraphRepository MongoTemplate Neo4jTemplate Embedded REST JPA Mongo Java Driver JDBC RDBMS MongoDB Neo4j … codecentric AG 27
  • 28.
    Spring Data MongoDB Template Abstraktion vom MongoDB Java Driver Konfiguration von mongod / mongos-Instanzen und Collections Verwaltung von Collections Map/Reduce-Aufrufe Object Mapping Annotationen @Document, @Field, @Index etc. Klassen werden auf Collections abgebildet, Java-Objekte auf Dokumente Repository Support Schlüsselwörter werden auf Query-Operatoren abgebildet Geospatial Queries codecentric AG 28
  • 29.
    MongoDB User-Gruppen (MUGs) MongoDBUser-Gruppe Düsseldorf MongoDB User-Gruppe Berlin https://www.xing.com/net/mongodb-dus http://www.meetup.com/MUGBerlin/ @MongoDUS @MUGBerlin MongoDB User-Gruppe Frankfurt/Main Hamburg MongoDB User Group https://www.xing.com/net/mongodb-ffm https://www.xing.com/net/mugh @MongoFFM MongoDB User-Gruppe München http://www.meetup.com/Muenchen-MongoDB-User-Group/ @mongomuc codecentric AG 29
  • 30.
    QUESTION? Tobias Trelle codecentric AG MerscheiderStr. 1 42699 Solingen tel +49 (0) 212.233628.47 fax +49 (0) 212.233628.79 mail Tobias.Trelle@codecentric.de twitter @tobiastrelle www.codecentric.de blog.codecentric.de/en/author/tobias-trelle www.xing.com/net/mongodb-dus codecentric AG 30