SlideShare a Scribd company logo
Building Apps With


Nate Abele
IPC — 1 June 2010
Berlin
X
Me


Former lead developer, CakePHP
Lead developer, Lithium
Twitter: @nateabele
“Alternative” databases?
What’s the point?

 Relational databases » relational algebra » set theory
 ORM “impedance mismatch”
 Failed alternatives reinforced the status quo
What’s a document database?


Composed of documents ...duh
Each document is heterogenous, and may have a
completely unique structure compared to other
documents
...That’s pretty much it
Why Mongo?

                   .org :

“The best features of document databases,
key-value stores, and relational databases.”
Mongo is...


 Fast
 Smart
 Scalable
Terminology


Database   »   Database

Table      »   Collection

Row        »   Document
Common Tasks
       tags
  id
                        MySQL
  name


   posts_tags
  id                    posts    comments
  post_id       id              id
  tag_id        title           post_id
                slug            author
                body            email
                published       body
                created         created
                updated
Common Tasks       id
                           posts

                   title
                   slug
         MongoDB   body
                   published
                   created
                   updated

                           comments
                            author
                            email
                            body
                            created


                           tags
Common Tasks
MongoDB
{
    "_id" : ObjectId("4c03e856e258c2701930c091"),
    "title" : "Welcome to MongoDB",
    "slug" : "welcome-to-mongodb",
    "body" : "Today, we're gonna totally rock your world...",
    "published" : true,
    "created" : "Mon May 31 2010 12:48:22 GMT-0400 (EDT)",
    "updated" : "Mon May 31 2010 12:48:22 GMT-0400 (EDT)",
    "comments" : [
        {
            "author" : "Bob",
            "email" : "bob@example.com",
            "body" : "My mind has been totally blown!",
            "created" : "Mon May 31 2010 12:48:22 GMT-0400 (EDT)"
        }
    ],
    "tags" : [
        "databases", "MongoDB", "awesome"
    ]
}
[...frantic hand-wringing ensues...]
[...pause, deep breath...]
Doing the “normal db” stuff
How do I...

 ...do pattern-matching?
 db.posts.find({ "title" : /mongodb/i })


 ...find all posts tagged ‘MongoDB’?
 db.posts.find({ "tags" : "MongoDB" })


 ...find all Bob’s comments?
 db.posts.find({ "comments.email" : "bob@example.com" })
Doing the “normal db” stuff
How do I...



 ...change Bob’s email?
 db.posts.update(
     { "comments.email": "bob@example.com" },
     { $set : { "comments.$.email" : "robert@example.com" }}
 )
$set?
Querying
$gt     $all
$gte	   $size
$lt	    $exists
$lte	   $type
$ne	    $elemMatch
$in	    $not
$nin	   $where
$mod
Querying
dontTrust = db.people.find({
  “age”: { $gt : 30 }
})
awesome = db.posts.find({ “tags” : {
  $in : [‘MongoDB’, ‘awesome’]
}})
todo = db.tasks.find({
  “status” : { $nin : [
    ‘In Progress’, ‘Completed‘
  ]}
})
Querying
By arbitrary function:
db.posts.find({ $where: function() {
    return this.hits % 2 == 0;
}})

By grouping key:
db.posts.group({
    "key": { "hits": true },
    "initial": { count: 0 },
    "reduce": function(obj, prev) {
       prev.count++;
    }
});
Querying
By grouping function:
db.photos.group({
  keyf: function(o) {
     return {
       hits: Math.round(o.hits / 1000)
     };
  },
  "initial": { count: 0 },
  "reduce": function(obj, prev) {
     prev.count++;
  }
});
Grouping results
[
    { 'hits' => 0, 'count' => 5 },
    { 'hits' => 1, 'count' => 4 },
    { 'hits' => 2, 'count' => 7 },
    ...
]
Map/reduce


...with apologies to John Nunemaker.
Map/reduce
>   db.items.insert({tags:   ['dog', 'cat']})
>   db.items.insert({tags:   ['dog']})
>   db.items.insert({tags:   ['dog', 'mouse']})
>   db.items.insert({tags:   ['dog', 'mouse', 'hippo']})
>   db.items.insert({tags:   ['dog', 'mouse', 'hippo']})
>   db.items.insert({tags:   ['dog', 'hippo']})
Map/reduce
> var map = function() {
    this.tags.forEach(function(t) {
      emit(t, {count: 1});
    });
}
Map/reduce
> var reduce = function(key, val) {
  var count = 0;
  for(var i = 0, len = val.length; i < len; i++) {
    count += val[i].count;
  }
  return { count: count };
}
Map/reduce


> var result = db.items.mapReduce(map, reduce);
Map/reduce
{
    "ok" : 1,
    "timeMillis" : 86,
    "result" : "tmp.mr.mapreduce_1273861517_683",
    "counts" : {
       "input" : 6,
       "emit" : 13,
       "output" : 4
    }
}
Map/reduce
db["tmp.mr.mapreduce_1273861517_683"].find()


{   "_id"   :   "cat",	"value" :   {   "count" :   1   }   }
{   "_id"   :   "dog",	"value" :   {   "count" :   6   }   }
{   "_id"   :   "hippo", "value"   :   { "count"   :   3   } }
{   "_id"   :   "mouse", "value"   :   { "count"   :   3   } }
Atomic Operations

Incrementing & decrementing: $inc:
  db.posts.update(
    { _id : new ObjectId("4c041e...30c093") },
    { $inc : { "hits" : 1 }}
  )

  db.posts.update(
    { _id : new ObjectId("4c041e...30c093") },
    { $inc : { "hits" : -1 }}
  )
Atomic Operations


Adding, updating & removing: $set & $unset:
 db.posts.update({}, { $set : { "hits" : 0 }})

 db.posts.update({}, { $unset : { "hits" : 1 }})
Atomic Operations

Array operations: $push[All], $pull[All],
$addToSet & $pop:

 db.posts.update({ "tags": "MongoDB" }, {
    $push: { "tags" : "awesome" }
 })

 db.posts.update({ "tags": "MySQL" }, {
    $pull: { "tags" : "awesome" }
 })
Atomic Operations
Array operations: $push[All], $pull[All],
$addToSet & $pop:

 db.queues.update(
   { _id : new ObjectId("4c041e...30c093") },
   { $pop: { "operations" : 1 }}
 )

 db.todos.update(
    { _id : new ObjectId("4c041e...30c093") },
    { $pop: { "listItems" : -1 }}
 )
Indexes


Slows write performance, but greatly improves reads
For best results, index on what you query on
Mongo likes to fit its indexes in memory
Indexes

db.users.ensureIndex({ “email”: 1 })
db.posts.ensureIndex({ “tags”: 1 })
db.posts.ensureIndex({ “created”: -1 })
db.posts.ensureIndex({
   “tags”: 1,
   “created”: -1
})
Indexes

“unique” / “dropDups”: ensure uniqueness
“safe”: Make sure it worked. Else, panic.
“name”: Mostly for troubleshooting
“background”:
 Best. Performance. Panic. Button. Ever.
Indexes
When in doubt, explain()
{   "cursor" : "BtreeCursor hits_1 multi",
    "indexBounds" : [
       [{ "hits" : 0 }, { "hits" : 0 }],
       [{ "hits" : 1 }, { "hits" : 1 }]
    ],
    "nscanned" : 1,
    "nscannedObjects" : 1,
    "n" : 1,
    "millis" : 35,
    "allPlans" : [
       {
          "cursor" : "BtreeCursor hits_1 multi",
          "indexBounds" : [
             [{ "hits" : 0 }, { "hits" : 0 }],
             [{ "hits" : 1 }, { "hits" : 1 }]
          ]
       }
    ]
}
Location, location, location
Location
MongoDB makes location-aware apps stupid-simple
First, add an index:

db.places.ensureIndex({ location: “2d” })
Go to town:

db.places.find({
  location: { $near : [
    40.79870933724115, -73.7656099560547
  ]}
})
Location
Location

db.places.find({
   location: { $within : { $box : {
   [
     [40.800788494123154,
      -73.85556051757814],
     [40.68008976560161,
      -74.04232809570314]
   ]
});
Easy to get started
 Up and running on most systems in a half-dozen
 commands or less fewer
 http://try.mongodb.org/
Coming to a platform near you
Drupal for MongoDB
http://drupal.org/project/mongodb

D7: mongodb_cache: Store cache items in mongodb

D7: mongodb_field_storage: Store the fields in mongodb

D7: mongodb_session: Store sessions in mongodb

D6/D7: mongodb_watchdog: Store the watchdog messages in mongodb

D6/D7: mongodb: support library for the other modules

D7: mongodb_block: Store block information in mongodb. Very close to the core
block API

D7: mongodb_queue: DrupalQueueInterface implementation using mongodb

http://sf2010.drupal.org/conference/sessions/mongodb-humongous-drupal
Even MORE Drupal

Work to get listing API into core:
http://drupal.org/node/780154
Experimental goodies to play with:
http://drupalcode.org/viewvc/drupal/contributions/
sandbox/chx/dbtng_mongo_experimental/
Joomla!


MongoDB helper library for Joomla!
Branch of 1.6 development for alternative query builder
Full MongoDB support most likely in 2.0
Lithium PHP framework

MongoDB native support since 0.2
http://rad-dev.org/lithium/wiki
Projects demonstrating MongoDB support:
  http://rad-dev.org/lithium_mongo/source
  http://rad-dev.org/lithium_blog/source
CakePHP framework

MongoDB datasource
http://github.com/ichikaway/mongoDB-Datasource
Example article
http://mark-story.com/posts/view/using-mongodb-
with-cakephp
MongoDB Language Center
http://www.mongodb.org/display/DOCS/Drivers
Community Resources
http://www.mongodb.org/display/DOCS/
Community
Development Tracker
http://jira.mongodb.org
MongoDB Cookbook
http://cookbook.mongodb.org/
Thanks!
{
    email:    “nate.abele@gmail.com”,
    twitter: “@nateabele”,
    web:      “http://lithify.me/”,
    slides:   “http://www.slideshare.net/nateabele”
}

More Related Content

What's hot

Back to Basics Webinar 2: Your First MongoDB Application
Back to Basics Webinar 2: Your First MongoDB ApplicationBack to Basics Webinar 2: Your First MongoDB Application
Back to Basics Webinar 2: Your First MongoDB Application
MongoDB
 
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
antoinegirbal
 
Map/Confused? A practical approach to Map/Reduce with MongoDB
Map/Confused? A practical approach to Map/Reduce with MongoDBMap/Confused? A practical approach to Map/Reduce with MongoDB
Map/Confused? A practical approach to Map/Reduce with MongoDB
Uwe Printz
 
Practical Ruby Projects With Mongo Db
Practical Ruby Projects With Mongo DbPractical Ruby Projects With Mongo Db
Practical Ruby Projects With Mongo Db
Alex Sharp
 
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 presentationMurat Çakal
 
Mongo Presentation by Metatagg Solutions
Mongo Presentation by Metatagg SolutionsMongo Presentation by Metatagg Solutions
Mongo Presentation by Metatagg Solutions
Metatagg Solutions
 
An introduction to MongoDB
An introduction to MongoDBAn introduction to MongoDB
An introduction to MongoDB
Universidade de São Paulo
 
PhpstudyTokyo MongoDB PHP CakePHP
PhpstudyTokyo MongoDB PHP CakePHPPhpstudyTokyo MongoDB PHP CakePHP
PhpstudyTokyo MongoDB PHP CakePHP
ichikaway
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDBAlex Bilbie
 
MongoDB and Ruby on Rails
MongoDB and Ruby on RailsMongoDB and Ruby on Rails
MongoDB and Ruby on Railsrfischer20
 
Back to Basics Webinar 4: Advanced Indexing, Text and Geospatial Indexes
Back to Basics Webinar 4: Advanced Indexing, Text and Geospatial IndexesBack to Basics Webinar 4: Advanced Indexing, Text and Geospatial Indexes
Back to Basics Webinar 4: Advanced Indexing, Text and Geospatial Indexes
MongoDB
 
Webinar: Schema Design
Webinar: Schema DesignWebinar: Schema Design
Webinar: Schema Design
MongoDB
 
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
Mike Friedman
 
Learn Learn how to build your mobile back-end with MongoDB
Learn Learn how to build your mobile back-end with MongoDBLearn Learn how to build your mobile back-end with MongoDB
Learn Learn how to build your mobile back-end with MongoDB
Marakana Inc.
 
MongoDB
MongoDBMongoDB
Mongo db queries
Mongo db queriesMongo db queries
Mongo db queries
ssuser6d5faa
 
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
Stennie Steneker
 
Introduction to MongoDB and Hadoop
Introduction to MongoDB and HadoopIntroduction to MongoDB and Hadoop
Introduction to MongoDB and Hadoop
Steven Francia
 

What's hot (20)

Back to Basics Webinar 2: Your First MongoDB Application
Back to Basics Webinar 2: Your First MongoDB ApplicationBack to Basics Webinar 2: Your First MongoDB Application
Back to Basics Webinar 2: Your First MongoDB Application
 
MongoDB and hadoop
MongoDB and hadoopMongoDB and hadoop
MongoDB and hadoop
 
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
 
Map/Confused? A practical approach to Map/Reduce with MongoDB
Map/Confused? A practical approach to Map/Reduce with MongoDBMap/Confused? A practical approach to Map/Reduce with MongoDB
Map/Confused? A practical approach to Map/Reduce with MongoDB
 
Practical Ruby Projects With Mongo Db
Practical Ruby Projects With Mongo DbPractical Ruby Projects With Mongo Db
Practical Ruby Projects With Mongo Db
 
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
 
Mongo Presentation by Metatagg Solutions
Mongo Presentation by Metatagg SolutionsMongo Presentation by Metatagg Solutions
Mongo Presentation by Metatagg Solutions
 
An introduction to MongoDB
An introduction to MongoDBAn introduction to MongoDB
An introduction to MongoDB
 
Indexing
IndexingIndexing
Indexing
 
PhpstudyTokyo MongoDB PHP CakePHP
PhpstudyTokyo MongoDB PHP CakePHPPhpstudyTokyo MongoDB PHP CakePHP
PhpstudyTokyo MongoDB PHP CakePHP
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
MongoDB and Ruby on Rails
MongoDB and Ruby on RailsMongoDB and Ruby on Rails
MongoDB and Ruby on Rails
 
Back to Basics Webinar 4: Advanced Indexing, Text and Geospatial Indexes
Back to Basics Webinar 4: Advanced Indexing, Text and Geospatial IndexesBack to Basics Webinar 4: Advanced Indexing, Text and Geospatial Indexes
Back to Basics Webinar 4: Advanced Indexing, Text and Geospatial Indexes
 
Webinar: Schema Design
Webinar: Schema DesignWebinar: Schema Design
Webinar: Schema Design
 
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
 
Learn Learn how to build your mobile back-end with MongoDB
Learn Learn how to build your mobile back-end with MongoDBLearn Learn how to build your mobile back-end with MongoDB
Learn Learn how to build your mobile back-end with MongoDB
 
MongoDB
MongoDBMongoDB
MongoDB
 
Mongo db queries
Mongo db queriesMongo db queries
Mongo db queries
 
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
 
Introduction to MongoDB and Hadoop
Introduction to MongoDB and HadoopIntroduction to MongoDB and Hadoop
Introduction to MongoDB and Hadoop
 

Viewers also liked

Web Services
Web ServicesWeb Services
Web Services
chidi
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium Apps
Nate Abele
 
Measuring Your Code
Measuring Your CodeMeasuring Your Code
Measuring Your Code
Nate Abele
 
Measuring Your Code 2.0
Measuring Your Code 2.0Measuring Your Code 2.0
Measuring Your Code 2.0
Nate Abele
 
Practical PHP 5.3
Practical PHP 5.3Practical PHP 5.3
Practical PHP 5.3
Nate Abele
 
Web Service Basics and NWS Setup
Web Service  Basics and NWS SetupWeb Service  Basics and NWS Setup
Web Service Basics and NWS Setup
Northeastern University
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
Nate Abele
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Nate Abele
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
Nate Abele
 
Best practices for RESTful web service design
Best practices for RESTful web service designBest practices for RESTful web service design
Best practices for RESTful web service design
Ramin Orujov
 
A Beginners Guide to noSQL
A Beginners Guide to noSQLA Beginners Guide to noSQL
A Beginners Guide to noSQL
Mike Crabb
 

Viewers also liked (11)

Web Services
Web ServicesWeb Services
Web Services
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium Apps
 
Measuring Your Code
Measuring Your CodeMeasuring Your Code
Measuring Your Code
 
Measuring Your Code 2.0
Measuring Your Code 2.0Measuring Your Code 2.0
Measuring Your Code 2.0
 
Practical PHP 5.3
Practical PHP 5.3Practical PHP 5.3
Practical PHP 5.3
 
Web Service Basics and NWS Setup
Web Service  Basics and NWS SetupWeb Service  Basics and NWS Setup
Web Service Basics and NWS Setup
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 
Best practices for RESTful web service design
Best practices for RESTful web service designBest practices for RESTful web service design
Best practices for RESTful web service design
 
A Beginners Guide to noSQL
A Beginners Guide to noSQLA Beginners Guide to noSQL
A Beginners Guide to noSQL
 

Similar to Building Apps with MongoDB

MongoDB
MongoDBMongoDB
MongoDB
Steve Klabnik
 
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
Steven Francia
 
MongoDB at ZPUGDC
MongoDB at ZPUGDCMongoDB at ZPUGDC
MongoDB at ZPUGDC
Mike Dirolf
 
Managing Social Content with MongoDB
Managing Social Content with MongoDBManaging Social Content with MongoDB
Managing Social Content with MongoDB
MongoDB
 
San Francisco Java User Group
San Francisco Java User GroupSan Francisco Java User Group
San Francisco Java User Groupkchodorow
 
10gen Presents Schema Design and Data Modeling
10gen Presents Schema Design and Data Modeling10gen Presents Schema Design and Data Modeling
10gen Presents Schema Design and Data ModelingDATAVERSITY
 
Marc s01 e02-crud-database
Marc s01 e02-crud-databaseMarc s01 e02-crud-database
Marc s01 e02-crud-databaseMongoDB
 
Webinarserie: Einführung in MongoDB: “Back to Basics” - Teil 3 - Interaktion ...
Webinarserie: Einführung in MongoDB: “Back to Basics” - Teil 3 - Interaktion ...Webinarserie: Einführung in MongoDB: “Back to Basics” - Teil 3 - Interaktion ...
Webinarserie: Einführung in MongoDB: “Back to Basics” - Teil 3 - Interaktion ...MongoDB
 
Back to Basics, webinar 2: La tua prima applicazione MongoDB
Back to Basics, webinar 2: La tua prima applicazione MongoDBBack to Basics, webinar 2: La tua prima applicazione MongoDB
Back to Basics, webinar 2: La tua prima applicazione MongoDB
MongoDB
 
Starting with MongoDB
Starting with MongoDBStarting with MongoDB
Starting with MongoDB
DoThinger
 
Back to Basics: My First MongoDB Application
Back to Basics: My First MongoDB ApplicationBack to Basics: My First MongoDB Application
Back to Basics: My First MongoDB Application
MongoDB
 
Back to Basics 2017 - Your First MongoDB Application
Back to Basics 2017 - Your First MongoDB ApplicationBack to Basics 2017 - Your First MongoDB Application
Back to Basics 2017 - Your First MongoDB Application
Joe Drumgoole
 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDB
MongoDB
 
Building your first app with MongoDB
Building your first app with MongoDBBuilding your first app with MongoDB
Building your first app with MongoDB
Norberto Leite
 
MongoDB for Coder Training (Coding Serbia 2013)
MongoDB for Coder Training (Coding Serbia 2013)MongoDB for Coder Training (Coding Serbia 2013)
MongoDB for Coder Training (Coding Serbia 2013)
Uwe Printz
 
MongoDB - Back to Basics - La tua prima Applicazione
MongoDB - Back to Basics - La tua prima ApplicazioneMongoDB - Back to Basics - La tua prima Applicazione
MongoDB - Back to Basics - La tua prima Applicazione
Massimo Brignoli
 
Back to basics Italian webinar 2 Mia prima applicazione MongoDB
Back to basics Italian webinar 2  Mia prima applicazione MongoDBBack to basics Italian webinar 2  Mia prima applicazione MongoDB
Back to basics Italian webinar 2 Mia prima applicazione MongoDB
MongoDB
 
Pyconie 2012
Pyconie 2012Pyconie 2012
Pyconie 2012Yaqi Zhao
 

Similar to Building Apps with MongoDB (20)

Latinoware
LatinowareLatinoware
Latinoware
 
MongoDB
MongoDBMongoDB
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 at ZPUGDC
MongoDB at ZPUGDCMongoDB at ZPUGDC
MongoDB at ZPUGDC
 
Managing Social Content with MongoDB
Managing Social Content with MongoDBManaging Social Content with MongoDB
Managing Social Content with MongoDB
 
San Francisco Java User Group
San Francisco Java User GroupSan Francisco Java User Group
San Francisco Java User Group
 
10gen Presents Schema Design and Data Modeling
10gen Presents Schema Design and Data Modeling10gen Presents Schema Design and Data Modeling
10gen Presents Schema Design and Data Modeling
 
Marc s01 e02-crud-database
Marc s01 e02-crud-databaseMarc s01 e02-crud-database
Marc s01 e02-crud-database
 
Webinarserie: Einführung in MongoDB: “Back to Basics” - Teil 3 - Interaktion ...
Webinarserie: Einführung in MongoDB: “Back to Basics” - Teil 3 - Interaktion ...Webinarserie: Einführung in MongoDB: “Back to Basics” - Teil 3 - Interaktion ...
Webinarserie: Einführung in MongoDB: “Back to Basics” - Teil 3 - Interaktion ...
 
Back to Basics, webinar 2: La tua prima applicazione MongoDB
Back to Basics, webinar 2: La tua prima applicazione MongoDBBack to Basics, webinar 2: La tua prima applicazione MongoDB
Back to Basics, webinar 2: La tua prima applicazione MongoDB
 
Starting with MongoDB
Starting with MongoDBStarting with MongoDB
Starting with MongoDB
 
Back to Basics: My First MongoDB Application
Back to Basics: My First MongoDB ApplicationBack to Basics: My First MongoDB Application
Back to Basics: My First MongoDB Application
 
Back to Basics 2017 - Your First MongoDB Application
Back to Basics 2017 - Your First MongoDB ApplicationBack to Basics 2017 - Your First MongoDB Application
Back to Basics 2017 - Your First MongoDB Application
 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDB
 
Building your first app with MongoDB
Building your first app with MongoDBBuilding your first app with MongoDB
Building your first app with MongoDB
 
The emerging world of mongo db csp
The emerging world of mongo db   cspThe emerging world of mongo db   csp
The emerging world of mongo db csp
 
MongoDB for Coder Training (Coding Serbia 2013)
MongoDB for Coder Training (Coding Serbia 2013)MongoDB for Coder Training (Coding Serbia 2013)
MongoDB for Coder Training (Coding Serbia 2013)
 
MongoDB - Back to Basics - La tua prima Applicazione
MongoDB - Back to Basics - La tua prima ApplicazioneMongoDB - Back to Basics - La tua prima Applicazione
MongoDB - Back to Basics - La tua prima Applicazione
 
Back to basics Italian webinar 2 Mia prima applicazione MongoDB
Back to basics Italian webinar 2  Mia prima applicazione MongoDBBack to basics Italian webinar 2  Mia prima applicazione MongoDB
Back to basics Italian webinar 2 Mia prima applicazione MongoDB
 
Pyconie 2012
Pyconie 2012Pyconie 2012
Pyconie 2012
 

Recently uploaded

State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 

Recently uploaded (20)

State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 

Building Apps with MongoDB

  • 1. Building Apps With Nate Abele IPC — 1 June 2010 Berlin
  • 2.
  • 3. X
  • 4. Me Former lead developer, CakePHP Lead developer, Lithium Twitter: @nateabele
  • 5. “Alternative” databases? What’s the point? Relational databases » relational algebra » set theory ORM “impedance mismatch” Failed alternatives reinforced the status quo
  • 6. What’s a document database? Composed of documents ...duh Each document is heterogenous, and may have a completely unique structure compared to other documents ...That’s pretty much it
  • 7. Why Mongo? .org : “The best features of document databases, key-value stores, and relational databases.”
  • 8. Mongo is... Fast Smart Scalable
  • 9. Terminology Database » Database Table » Collection Row » Document
  • 10. Common Tasks tags id MySQL name posts_tags id posts comments post_id id id tag_id title post_id slug author body email published body created created updated
  • 11. Common Tasks id posts title slug MongoDB body published created updated comments author email body created tags
  • 12. Common Tasks MongoDB { "_id" : ObjectId("4c03e856e258c2701930c091"), "title" : "Welcome to MongoDB", "slug" : "welcome-to-mongodb", "body" : "Today, we're gonna totally rock your world...", "published" : true, "created" : "Mon May 31 2010 12:48:22 GMT-0400 (EDT)", "updated" : "Mon May 31 2010 12:48:22 GMT-0400 (EDT)", "comments" : [ { "author" : "Bob", "email" : "bob@example.com", "body" : "My mind has been totally blown!", "created" : "Mon May 31 2010 12:48:22 GMT-0400 (EDT)" } ], "tags" : [ "databases", "MongoDB", "awesome" ] }
  • 15. Doing the “normal db” stuff How do I... ...do pattern-matching? db.posts.find({ "title" : /mongodb/i }) ...find all posts tagged ‘MongoDB’? db.posts.find({ "tags" : "MongoDB" }) ...find all Bob’s comments? db.posts.find({ "comments.email" : "bob@example.com" })
  • 16. Doing the “normal db” stuff How do I... ...change Bob’s email? db.posts.update( { "comments.email": "bob@example.com" }, { $set : { "comments.$.email" : "robert@example.com" }} )
  • 17. $set?
  • 18. Querying $gt $all $gte $size $lt $exists $lte $type $ne $elemMatch $in $not $nin $where $mod
  • 19. Querying dontTrust = db.people.find({ “age”: { $gt : 30 } }) awesome = db.posts.find({ “tags” : { $in : [‘MongoDB’, ‘awesome’] }}) todo = db.tasks.find({ “status” : { $nin : [ ‘In Progress’, ‘Completed‘ ]} })
  • 20. Querying By arbitrary function: db.posts.find({ $where: function() { return this.hits % 2 == 0; }}) By grouping key: db.posts.group({ "key": { "hits": true }, "initial": { count: 0 }, "reduce": function(obj, prev) { prev.count++; } });
  • 21. Querying By grouping function: db.photos.group({ keyf: function(o) { return { hits: Math.round(o.hits / 1000) }; }, "initial": { count: 0 }, "reduce": function(obj, prev) { prev.count++; } });
  • 22. Grouping results [ { 'hits' => 0, 'count' => 5 }, { 'hits' => 1, 'count' => 4 }, { 'hits' => 2, 'count' => 7 }, ... ]
  • 24. Map/reduce > db.items.insert({tags: ['dog', 'cat']}) > db.items.insert({tags: ['dog']}) > db.items.insert({tags: ['dog', 'mouse']}) > db.items.insert({tags: ['dog', 'mouse', 'hippo']}) > db.items.insert({tags: ['dog', 'mouse', 'hippo']}) > db.items.insert({tags: ['dog', 'hippo']})
  • 25. Map/reduce > var map = function() { this.tags.forEach(function(t) { emit(t, {count: 1}); }); }
  • 26. Map/reduce > var reduce = function(key, val) { var count = 0; for(var i = 0, len = val.length; i < len; i++) { count += val[i].count; } return { count: count }; }
  • 27. Map/reduce > var result = db.items.mapReduce(map, reduce);
  • 28. Map/reduce { "ok" : 1, "timeMillis" : 86, "result" : "tmp.mr.mapreduce_1273861517_683", "counts" : { "input" : 6, "emit" : 13, "output" : 4 } }
  • 29. Map/reduce db["tmp.mr.mapreduce_1273861517_683"].find() { "_id" : "cat", "value" : { "count" : 1 } } { "_id" : "dog", "value" : { "count" : 6 } } { "_id" : "hippo", "value" : { "count" : 3 } } { "_id" : "mouse", "value" : { "count" : 3 } }
  • 30. Atomic Operations Incrementing & decrementing: $inc: db.posts.update( { _id : new ObjectId("4c041e...30c093") }, { $inc : { "hits" : 1 }} ) db.posts.update( { _id : new ObjectId("4c041e...30c093") }, { $inc : { "hits" : -1 }} )
  • 31. Atomic Operations Adding, updating & removing: $set & $unset: db.posts.update({}, { $set : { "hits" : 0 }}) db.posts.update({}, { $unset : { "hits" : 1 }})
  • 32. Atomic Operations Array operations: $push[All], $pull[All], $addToSet & $pop: db.posts.update({ "tags": "MongoDB" }, { $push: { "tags" : "awesome" } }) db.posts.update({ "tags": "MySQL" }, { $pull: { "tags" : "awesome" } })
  • 33. Atomic Operations Array operations: $push[All], $pull[All], $addToSet & $pop: db.queues.update( { _id : new ObjectId("4c041e...30c093") }, { $pop: { "operations" : 1 }} ) db.todos.update( { _id : new ObjectId("4c041e...30c093") }, { $pop: { "listItems" : -1 }} )
  • 34. Indexes Slows write performance, but greatly improves reads For best results, index on what you query on Mongo likes to fit its indexes in memory
  • 35. Indexes db.users.ensureIndex({ “email”: 1 }) db.posts.ensureIndex({ “tags”: 1 }) db.posts.ensureIndex({ “created”: -1 }) db.posts.ensureIndex({ “tags”: 1, “created”: -1 })
  • 36. Indexes “unique” / “dropDups”: ensure uniqueness “safe”: Make sure it worked. Else, panic. “name”: Mostly for troubleshooting “background”: Best. Performance. Panic. Button. Ever.
  • 37. Indexes When in doubt, explain() { "cursor" : "BtreeCursor hits_1 multi", "indexBounds" : [ [{ "hits" : 0 }, { "hits" : 0 }], [{ "hits" : 1 }, { "hits" : 1 }] ], "nscanned" : 1, "nscannedObjects" : 1, "n" : 1, "millis" : 35, "allPlans" : [ { "cursor" : "BtreeCursor hits_1 multi", "indexBounds" : [ [{ "hits" : 0 }, { "hits" : 0 }], [{ "hits" : 1 }, { "hits" : 1 }] ] } ] }
  • 39. Location MongoDB makes location-aware apps stupid-simple First, add an index: db.places.ensureIndex({ location: “2d” }) Go to town: db.places.find({ location: { $near : [ 40.79870933724115, -73.7656099560547 ]} })
  • 41. Location db.places.find({ location: { $within : { $box : { [ [40.800788494123154, -73.85556051757814], [40.68008976560161, -74.04232809570314] ] });
  • 42. Easy to get started Up and running on most systems in a half-dozen commands or less fewer http://try.mongodb.org/
  • 43. Coming to a platform near you
  • 44. Drupal for MongoDB http://drupal.org/project/mongodb D7: mongodb_cache: Store cache items in mongodb D7: mongodb_field_storage: Store the fields in mongodb D7: mongodb_session: Store sessions in mongodb D6/D7: mongodb_watchdog: Store the watchdog messages in mongodb D6/D7: mongodb: support library for the other modules D7: mongodb_block: Store block information in mongodb. Very close to the core block API D7: mongodb_queue: DrupalQueueInterface implementation using mongodb http://sf2010.drupal.org/conference/sessions/mongodb-humongous-drupal
  • 45. Even MORE Drupal Work to get listing API into core: http://drupal.org/node/780154 Experimental goodies to play with: http://drupalcode.org/viewvc/drupal/contributions/ sandbox/chx/dbtng_mongo_experimental/
  • 46. Joomla! MongoDB helper library for Joomla! Branch of 1.6 development for alternative query builder Full MongoDB support most likely in 2.0
  • 47. Lithium PHP framework MongoDB native support since 0.2 http://rad-dev.org/lithium/wiki Projects demonstrating MongoDB support: http://rad-dev.org/lithium_mongo/source http://rad-dev.org/lithium_blog/source
  • 48. CakePHP framework MongoDB datasource http://github.com/ichikaway/mongoDB-Datasource Example article http://mark-story.com/posts/view/using-mongodb- with-cakephp
  • 53. Thanks! { email: “nate.abele@gmail.com”, twitter: “@nateabele”, web: “http://lithify.me/”, slides: “http://www.slideshare.net/nateabele” }