SlideShare ist ein Scribd-Unternehmen logo
1 von 72
Downloaden Sie, um offline zu lesen
Getting Started With
                         MongoDB
                         { author: “Ynon Perek” }




Friday, December 7, 12
Whoami




                     Ynon Perek

                     http://ynonperek.com

                     ynon@ynonperek.com




Friday, December 7, 12
Agenda


                              MongoDB Overview

                              Mongo Test Drive

                              Mongo Data Model

                              CRUD Operations

                              Working With Files




Friday, December 7, 12
MongoDB Overview



                  Data Store for
                  JSON Objects




Friday, December 7, 12
MongoDB Overview



                  Data Store for
                  JSON Objects


          {
               “Name” : “Rose Tyler”
          }




Friday, December 7, 12
JSON Objects



                     A JSON Object is a collection of key/value pairs

                     Keys are simple strings

                     Values can be: Numbers, Strings, Arrays, Other Objects,
                     and more




Friday, December 7, 12
JSON Examples


                     {
                         “name”: “The Doctor”,
                         “age”: 900
                     }

                     {
                         “race”: “human”,
                         “body parts” : [“head”, “legs”, “arms”, “eyes”]
                     }




Friday, December 7, 12
MongoDB Overview




                     A Document Oriented Database (No SQL)

                     No Joins

                     No Transactions




Friday, December 7, 12
Application Architecture




                          SERVER          DB




Friday, December 7, 12
Mongo Test Drive
                         Create MongoLab Account And Start Using The DB


Friday, December 7, 12
Install mongo Client



                     Download mongo from:
                     http://www.mongodb.org/downloads

                     Extract zip file

                     Run mongo




Friday, December 7, 12
Install mongo Client

                     Choose production release for your architecture




Friday, December 7, 12
Install mongo Client




                     Note: Still using Windows XP ? You’ll have to use the
                     previous 2.0 version




Friday, December 7, 12
Meet MongoLab




Friday, December 7, 12
Database Dashboard




Friday, December 7, 12
Create New Database



                     Choose database name

                     Choose provider

                     Choose plan (free is good)

                     Create a DB user




Friday, December 7, 12
Database Dashboard




Friday, December 7, 12
Connecting To The DB



                     There are two options to work with your new DB

                         You can use the web console

                         You can use the command line console

                     Let’s start with the web.




Friday, December 7, 12
Demo: Creating Documents


                     Create a few
                     documents on the web
                     console

                     Update the data

                     Delete some of them

                     Search by fields




Friday, December 7, 12
Mongo Data Model




                     DB Design for relational
                     database blog app

                     DB Design for Mongo-
                     based blog app




Friday, December 7, 12
Old-Style Table DB Design

             Name               Age       City of Birth




             Jim                22        Ashdod




             Mike               21        Eilat




Friday, December 7, 12
Problems With Tables


                     There are too many of them...




Friday, December 7, 12
Old-Style Table DB Design




Friday, December 7, 12
Cool MongoDB Design


             {
                  “title”: “Mongo 101”,
                  “author” : “ynonp”,
                  “comments” : [
                     { “author” : “...”, “content” : “...” },
                     { “author” : “...”, “content” : “...” }
                  ],
                  “tags” : [ “funny”, “informative”],
                  “content” : “...”
             }


Friday, December 7, 12
Mongo Schema



                     Use embedded documents or arrays

                     Less tables to access:

                         Better performance

                         Simple




Friday, December 7, 12
Q&A




Friday, December 7, 12
Lab


                     Create a DB for musical info

                     Create a collection called albums

                     Add info for 3 albums you like, including:

                         Album Name, Artist, Tracks, Release Date, Genres

                         Tracks is an array of objects

                         Genres is an array of strings




Friday, December 7, 12
CRUD Operations
                         Create, Read, Update and Destroy Data


Friday, December 7, 12
Mongo CRUD



                     Create   is called insert

                     Read     is called find

                     Update is called update

                     Destroy is called remove




Friday, December 7, 12
Mongo CRUD



                     From a developer’s perspective, MongoDB operations are
                     the same through the driver and through the console

                     In both cases, operations look like function calls or
                     method invocations

                     We’ll use mongo shell for the rest of this chapter




Friday, December 7, 12
Inserting Data




                     Use the command insert or save to insert a new object

                     db.collection.insert( obj );

                     db.collection.insert( array );




Friday, December 7, 12
Inserting Data




                     Inserting to a new collection creates the collection

                     Inserting an object with an _id key, it is used as the
                     object’s id (and must be unique).




Friday, December 7, 12
Reading Data


                     find and findOne perform read operations

                     Both take a query

                     find returns    a cursor

                     findOne returns an object           Optional: Fields to
                                                               fetch

                     db.collection.find( <query>, <projection> )




Friday, December 7, 12
Query Document



                     An empty (or missing) query document returns
                     everything

                     db.collection.find({})

                     db.collection.find()




Friday, December 7, 12
Query Document



                     Each key/value pair in the query document imposes a
                     condition on the results (objects that match).

                     db.movies.find({ “genre” : “indie” });

                     db.books.find({“pages” : { “$gt” : 100 }});




Friday, December 7, 12
Query Document

                                                        Query Object

                     Each key/value pair in the query document imposes a
                     condition on the results (objects that match).

                     db.movies.find({ “genre” : “indie” });

                     db.books.find({“pages” : { “$gt” : 100 }});




Friday, December 7, 12
Query Document


                     A compound query means a logical AND on the
                     conditions.

                     db.inventory.find(
                       {
                           “type” : “snacks”,
                           “available” : { “$lt” : 10 }
                       });




Friday, December 7, 12
Quiz: What Is Returned


                                         from      alterego   publisher

                                                   Bruce
                     {                   Earth                DC
                                                   Wayne
                         “publisher” :
                         “DC”
                     }                             Peter
                                         Earth                Marvel
                                                   Parker

                                         Krypton   Clark Kent DC



Friday, December 7, 12
Quiz: What Is Returned


                                         from      alterego   publisher

                     {                             Bruce
                         “publisher” :   Earth                DC
                                                   Wayne
                         “DC”,
                         “from” :
                         “Earth”                   Peter
                                         Earth                Marvel
                     }                             Parker

                                         Krypton   Clark Kent DC



Friday, December 7, 12
More Queries


                     You can use “$or” to have an OR expression

                     {
                         “$or” : [
                           { “type” : “food” },
                           { “type” : “drinks” }
                         ]
                     }




Friday, December 7, 12
Sub Documents


                     If your document has sub-documents, it’s possible to
                     query by a full sub document or look for a partial match

                     Full sub-document query means subdocument is exactly
                     as specified in the query

                     Example:

                     { ISBN : { “ISBN-10” : “1906465592”,
                                “ISBN-13” : “978-1906465599” }}




Friday, December 7, 12
Sub Documents


                     A partial query matches all objects that have at least the
                     required field (but may contain more)

                     Example:
                     {
                       “language.primary” : “english”
                     }

                     Value of language is an object, and it has a field called
                     primary




Friday, December 7, 12
Arrays



                     You can use an exact array match by providing the full
                     array in the query

                     Example:
                     {
                       tags : [ “funny”, “cute”, “cats” ]
                     }




Friday, December 7, 12
Arrays



                     You can query for an array that has at least one element
                     matching the query

                     Example:

                     { “tags” : “funny” }




Friday, December 7, 12
Arrays



                     If you have a subdocument as the element of an array,
                     it’s possible to query by its fields using the dot notation.

                     Examples:

                     { “tracks.4.name” : “Rose Mary Stretch” }

                     { “tracks.name”     : “Rose Mary Stretch” }




Friday, December 7, 12
Query Operators



                     Complex queries are performed with special operators.

                     These are reserved words starting with a $

                     Some of them: $gt, $gte, $lt, $lte, $ne, $in, $nin, $all,
                     $or, $not




Friday, December 7, 12
Comparator Queries



                     Value for key a is greater than 10
                     { “a” : { “$gt” : 10 }}

                     Value for key b is not 7
                     { “b” : { “$ne” : 7 }}

                     Value for key name is greater (ascii-wise) than ‘bird’
                     { “name” : { “$gt” : “bird” }}




Friday, December 7, 12
Queries: $in, $nin



                     Use $in to specify a choice from multiple options

                     Value for grade is 85, 90 or 100
                     { “grade” : { “$in” : [ 85, 90, 100 ] } }

                     Value for fruit is neither apple nor banana
                     { “fruit” : { “$nin” : [“apple”, “banana” ] } }




Friday, December 7, 12
Quiz: What Is Selected

                     { “reads” : { “$gt” : 10 },
                       “author” : { “$nin” : [“admin”, “manager”, “boss” ] } }



                     author             reads               title

                                                            How To Use
                     admin              99
                                                            Mongo
                                                            How To Make
                     Joe                120
                                                            Money
                                                            Windows
                     Jim                8
                                                            Manual

Friday, December 7, 12
Queries: $all




                     Select objects with array containing all elements

                     Example:
                     { “tags” : { “$all” : [ “funny”, “cats” ] } }




Friday, December 7, 12
More Query Operators


                     “$size” - array has a specific number of elements

                     “$exists” - field present or missing

                     Example:

                     { “friends” : { “$size” : 7 } }

                     { “producer” : { “$exists” : false } }




Friday, December 7, 12
Aggregation



                     count()    - returns how many objects found

                     distinct() - returns all distinct values for a key

                     Example:

                     db.posts.distinct( “tags” )




Friday, December 7, 12
Resources




                     Queries Cheat Sheet
                     http://www.10gen.com/sites/default/files/downloads/
                     mongodb_qrc_queries.pdf




Friday, December 7, 12
Q&A




Friday, December 7, 12
Lab


                     Using the previously defined musical DB. Query for:

                     Albums released after/before 2008

                     Albums with 7 tracks

                     Albums by a specific genre

                     Albums by a specific track name

                     Display ALL different genres in the DB




Friday, December 7, 12
Update



                     Update operations modify existing data in the DB

                     Mongo supports two update commands:
                     update() and save()

                     Update is the more general (and complex)




Friday, December 7, 12
Update




                     The general form for update is:


                     db.collection.update(
                       <query>, <update>, <options> )



              Which Entries                   What to do with
              to update                       them

Friday, December 7, 12
Update



                     The second argument to update() is an operator object

                     It tells update what to do with the data

                     Some keys you can use: “$set”, “$inc” “$push”,
                     “$pushAll”, “$addToSet”, “$pop”, “$pull”, “$pullAll”




Friday, December 7, 12
Update: set


                     $set modifies a value or add a new value

                     Example:

                     db.posts.update(
                        { title: “Why Is Your Cat Unhappy” },
                        { $set : { “archived” : true } }
                     );




Friday, December 7, 12
Quiz: $set



                     What happens here ?

                     db.cats.update(
                        { color: “white” },
                        { “$set” : { “owners” : [“John”, “Jim”] } }
                     );




Friday, December 7, 12
Quiz: $set


                     Update owners array of the first cat with white color

                     If you want to update all objects, use multi

                     db.cats.update(
                        { color: “white” },
                        { “$set” : { “owners” : [“John”, “Jim”] } }
                        { multi : true }
                     );




Friday, December 7, 12
Update: inc




                     $inc increases a numeric value

                     Example:

                     { “$inc” : { “age” : 11 } }




Friday, December 7, 12
Quiz: $inc



                     What happens here ?

                     db.songs.update(
                        { “title” : “Killing Lies” },
                        { “$inc” : { “plays” : 1 } }
                     );




Friday, December 7, 12
Update: push and pushAll


                     push() and pushAll() add items to an existing array

                     If they array did not exists, it is created

                     Example:

                     db.creatures.update(
                       { name: “The Doctor” },
                       { “$push” : { companions : “Rose Tyler” } }
                     )




Friday, December 7, 12
Update: addToSet



                     The $addToSet adds a new item only if it wasn’t already
                     in the array

                     Example:

                     { “$addToSet” : { “tags” : “funny” } }




Friday, December 7, 12
Update: pop


                     pop removes items of an array

                     Use a value of 1 to remove the last element

                     Use a value of -1 to remove the first element

                     Example:

                     { “$pop” : { “companions” : 1 } }




Friday, December 7, 12
Update: pull



                     Remove a specific item from an array.

                     Can use $pullAll to remove all matching elements

                     Example:

                     { “$pull” : { “companions” : “Rose Tyler” } }




Friday, December 7, 12
Updating with save()



                     The second update operation is save()

                     takes a document:

                         If the document has an id - update it

                         If not, insert it to the DB




Friday, December 7, 12
Deleting Data

                     remove() deletes objects from a collection

                     Takes a query and possibly a <justOne> arguments

                     Examples:

                     db.posts.remove({ “author” : “Father Angelo” })

                     db.music.remove({ “genres” : “pop” })

                     db.posts.remove({ “tags” : “funny” }, 1 );




Friday, December 7, 12
Q&A




Friday, December 7, 12
Lab


                     From the previous music database:

                         Add a new album with 4 tracks

                         Add a new track to that new album

                         Set property “plays” on all albums to 6

                         Increase it by 4 only for “indie” albums

                         Delete all “indie” music




Friday, December 7, 12
Thank You




                     Photos from: http://123rf.com

                     Slides available at: http://ynonperek.com




Friday, December 7, 12

Weitere ähnliche Inhalte

Ähnlich wie Introduction To MongoDB

Morning with MongoDB Paris 2012 - Accueil et Introductions
Morning with MongoDB Paris 2012 - Accueil et IntroductionsMorning with MongoDB Paris 2012 - Accueil et Introductions
Morning with MongoDB Paris 2012 - Accueil et IntroductionsMongoDB
 
Thomas risberg mongosv-2012-spring-data-cloud-foundry
Thomas risberg mongosv-2012-spring-data-cloud-foundryThomas risberg mongosv-2012-spring-data-cloud-foundry
Thomas risberg mongosv-2012-spring-data-cloud-foundrytrisberg
 
CloudFoundry and MongoDb, a marriage made in heaven
CloudFoundry and MongoDb, a marriage made in heavenCloudFoundry and MongoDb, a marriage made in heaven
CloudFoundry and MongoDb, a marriage made in heavenPatrick Chanezon
 
Webinar: MongoDB on the JVM
Webinar: MongoDB on the JVMWebinar: MongoDB on the JVM
Webinar: MongoDB on the JVMMongoDB
 
MongoTalk/Voyage
MongoTalk/VoyageMongoTalk/Voyage
MongoTalk/VoyageESUG
 
Node-IL Meetup 12/2
Node-IL Meetup 12/2Node-IL Meetup 12/2
Node-IL Meetup 12/2Ynon Perek
 
Mongo db php_shaken_not_stirred_joomlafrappe
Mongo db php_shaken_not_stirred_joomlafrappeMongo db php_shaken_not_stirred_joomlafrappe
Mongo db php_shaken_not_stirred_joomlafrappeSpyros Passas
 
Drupal and the rise of the documents
Drupal and the rise of the documentsDrupal and the rise of the documents
Drupal and the rise of the documentsClaudio Beatrice
 
MongoSV Schema Workshop
MongoSV Schema WorkshopMongoSV Schema Workshop
MongoSV Schema WorkshopMongoDB
 
Custom Android Code Templates
Custom Android Code TemplatesCustom Android Code Templates
Custom Android Code Templatesmurphonic
 
MongoDB Hadoop and Humongous Data
MongoDB Hadoop and Humongous DataMongoDB Hadoop and Humongous Data
MongoDB Hadoop and Humongous DataMongoDB
 
iOS Prototyping with Xcode Storyboards
iOS Prototyping with Xcode StoryboardsiOS Prototyping with Xcode Storyboards
iOS Prototyping with Xcode StoryboardsKyle Oba
 
Moving to Dojo 1.7 and the path to 2.0
Moving to Dojo 1.7 and the path to 2.0Moving to Dojo 1.7 and the path to 2.0
Moving to Dojo 1.7 and the path to 2.0James Thomas
 
Behat dpc12
Behat dpc12Behat dpc12
Behat dpc12benwaine
 
TripCase Unit Testing with Jasmine
TripCase Unit Testing with JasmineTripCase Unit Testing with Jasmine
TripCase Unit Testing with JasmineStephen Pond
 
JavaScript DOM Manipulations
JavaScript DOM ManipulationsJavaScript DOM Manipulations
JavaScript DOM ManipulationsYnon Perek
 

Ähnlich wie Introduction To MongoDB (20)

Everyday - mongodb
Everyday - mongodbEveryday - mongodb
Everyday - mongodb
 
Morning with MongoDB Paris 2012 - Accueil et Introductions
Morning with MongoDB Paris 2012 - Accueil et IntroductionsMorning with MongoDB Paris 2012 - Accueil et Introductions
Morning with MongoDB Paris 2012 - Accueil et Introductions
 
Thomas risberg mongosv-2012-spring-data-cloud-foundry
Thomas risberg mongosv-2012-spring-data-cloud-foundryThomas risberg mongosv-2012-spring-data-cloud-foundry
Thomas risberg mongosv-2012-spring-data-cloud-foundry
 
CloudFoundry and MongoDb, a marriage made in heaven
CloudFoundry and MongoDb, a marriage made in heavenCloudFoundry and MongoDb, a marriage made in heaven
CloudFoundry and MongoDb, a marriage made in heaven
 
Webinar: MongoDB on the JVM
Webinar: MongoDB on the JVMWebinar: MongoDB on the JVM
Webinar: MongoDB on the JVM
 
MongoTalk/Voyage
MongoTalk/VoyageMongoTalk/Voyage
MongoTalk/Voyage
 
Node-IL Meetup 12/2
Node-IL Meetup 12/2Node-IL Meetup 12/2
Node-IL Meetup 12/2
 
MongoDB
MongoDBMongoDB
MongoDB
 
Mongo db php_shaken_not_stirred_joomlafrappe
Mongo db php_shaken_not_stirred_joomlafrappeMongo db php_shaken_not_stirred_joomlafrappe
Mongo db php_shaken_not_stirred_joomlafrappe
 
Drupal and the rise of the documents
Drupal and the rise of the documentsDrupal and the rise of the documents
Drupal and the rise of the documents
 
Curious case of Dust
Curious case of DustCurious case of Dust
Curious case of Dust
 
MongoSV Schema Workshop
MongoSV Schema WorkshopMongoSV Schema Workshop
MongoSV Schema Workshop
 
Custom Android Code Templates
Custom Android Code TemplatesCustom Android Code Templates
Custom Android Code Templates
 
MongoDB Hadoop and Humongous Data
MongoDB Hadoop and Humongous DataMongoDB Hadoop and Humongous Data
MongoDB Hadoop and Humongous Data
 
iOS Prototyping with Xcode Storyboards
iOS Prototyping with Xcode StoryboardsiOS Prototyping with Xcode Storyboards
iOS Prototyping with Xcode Storyboards
 
Moving to Dojo 1.7 and the path to 2.0
Moving to Dojo 1.7 and the path to 2.0Moving to Dojo 1.7 and the path to 2.0
Moving to Dojo 1.7 and the path to 2.0
 
Behat dpc12
Behat dpc12Behat dpc12
Behat dpc12
 
TripCase Unit Testing with Jasmine
TripCase Unit Testing with JasmineTripCase Unit Testing with Jasmine
TripCase Unit Testing with Jasmine
 
JavaScript DOM Manipulations
JavaScript DOM ManipulationsJavaScript DOM Manipulations
JavaScript DOM Manipulations
 
Mongo db1
Mongo db1Mongo db1
Mongo db1
 

Mehr von Ynon Perek

09 performance
09 performance09 performance
09 performanceYnon Perek
 
Mobile Web Intro
Mobile Web IntroMobile Web Intro
Mobile Web IntroYnon Perek
 
Qt multi threads
Qt multi threadsQt multi threads
Qt multi threadsYnon Perek
 
Mobile Devices
Mobile DevicesMobile Devices
Mobile DevicesYnon Perek
 
Architecture app
Architecture appArchitecture app
Architecture appYnon Perek
 
Unit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsUnit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsYnon Perek
 
How to write easy-to-test JavaScript
How to write easy-to-test JavaScriptHow to write easy-to-test JavaScript
How to write easy-to-test JavaScriptYnon Perek
 
Introduction to Selenium and Ruby
Introduction to Selenium and RubyIntroduction to Selenium and Ruby
Introduction to Selenium and RubyYnon Perek
 
Introduction To Web Application Testing
Introduction To Web Application TestingIntroduction To Web Application Testing
Introduction To Web Application TestingYnon Perek
 
Qt Design Patterns
Qt Design PatternsQt Design Patterns
Qt Design PatternsYnon Perek
 
Web Application Security
Web Application SecurityWeb Application Security
Web Application SecurityYnon Perek
 

Mehr von Ynon Perek (20)

Regexp
RegexpRegexp
Regexp
 
Html5 intro
Html5 introHtml5 intro
Html5 intro
 
09 performance
09 performance09 performance
09 performance
 
Mobile Web Intro
Mobile Web IntroMobile Web Intro
Mobile Web Intro
 
Qt multi threads
Qt multi threadsQt multi threads
Qt multi threads
 
Vimperl
VimperlVimperl
Vimperl
 
Syllabus
SyllabusSyllabus
Syllabus
 
Mobile Devices
Mobile DevicesMobile Devices
Mobile Devices
 
Network
NetworkNetwork
Network
 
Architecture app
Architecture appArchitecture app
Architecture app
 
Cryptography
CryptographyCryptography
Cryptography
 
Unit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsUnit Testing JavaScript Applications
Unit Testing JavaScript Applications
 
How to write easy-to-test JavaScript
How to write easy-to-test JavaScriptHow to write easy-to-test JavaScript
How to write easy-to-test JavaScript
 
Introduction to Selenium and Ruby
Introduction to Selenium and RubyIntroduction to Selenium and Ruby
Introduction to Selenium and Ruby
 
Introduction To Web Application Testing
Introduction To Web Application TestingIntroduction To Web Application Testing
Introduction To Web Application Testing
 
Accessibility
AccessibilityAccessibility
Accessibility
 
Angularjs
AngularjsAngularjs
Angularjs
 
Js memory
Js memoryJs memory
Js memory
 
Qt Design Patterns
Qt Design PatternsQt Design Patterns
Qt Design Patterns
 
Web Application Security
Web Application SecurityWeb Application Security
Web Application Security
 

Introduction To MongoDB

  • 1. Getting Started With MongoDB { author: “Ynon Perek” } Friday, December 7, 12
  • 2. Whoami Ynon Perek http://ynonperek.com ynon@ynonperek.com Friday, December 7, 12
  • 3. Agenda MongoDB Overview Mongo Test Drive Mongo Data Model CRUD Operations Working With Files Friday, December 7, 12
  • 4. MongoDB Overview Data Store for JSON Objects Friday, December 7, 12
  • 5. MongoDB Overview Data Store for JSON Objects { “Name” : “Rose Tyler” } Friday, December 7, 12
  • 6. JSON Objects A JSON Object is a collection of key/value pairs Keys are simple strings Values can be: Numbers, Strings, Arrays, Other Objects, and more Friday, December 7, 12
  • 7. JSON Examples { “name”: “The Doctor”, “age”: 900 } { “race”: “human”, “body parts” : [“head”, “legs”, “arms”, “eyes”] } Friday, December 7, 12
  • 8. MongoDB Overview A Document Oriented Database (No SQL) No Joins No Transactions Friday, December 7, 12
  • 9. Application Architecture SERVER DB Friday, December 7, 12
  • 10. Mongo Test Drive Create MongoLab Account And Start Using The DB Friday, December 7, 12
  • 11. Install mongo Client Download mongo from: http://www.mongodb.org/downloads Extract zip file Run mongo Friday, December 7, 12
  • 12. Install mongo Client Choose production release for your architecture Friday, December 7, 12
  • 13. Install mongo Client Note: Still using Windows XP ? You’ll have to use the previous 2.0 version Friday, December 7, 12
  • 16. Create New Database Choose database name Choose provider Choose plan (free is good) Create a DB user Friday, December 7, 12
  • 18. Connecting To The DB There are two options to work with your new DB You can use the web console You can use the command line console Let’s start with the web. Friday, December 7, 12
  • 19. Demo: Creating Documents Create a few documents on the web console Update the data Delete some of them Search by fields Friday, December 7, 12
  • 20. Mongo Data Model DB Design for relational database blog app DB Design for Mongo- based blog app Friday, December 7, 12
  • 21. Old-Style Table DB Design Name Age City of Birth Jim 22 Ashdod Mike 21 Eilat Friday, December 7, 12
  • 22. Problems With Tables There are too many of them... Friday, December 7, 12
  • 23. Old-Style Table DB Design Friday, December 7, 12
  • 24. Cool MongoDB Design { “title”: “Mongo 101”, “author” : “ynonp”, “comments” : [ { “author” : “...”, “content” : “...” }, { “author” : “...”, “content” : “...” } ], “tags” : [ “funny”, “informative”], “content” : “...” } Friday, December 7, 12
  • 25. Mongo Schema Use embedded documents or arrays Less tables to access: Better performance Simple Friday, December 7, 12
  • 27. Lab Create a DB for musical info Create a collection called albums Add info for 3 albums you like, including: Album Name, Artist, Tracks, Release Date, Genres Tracks is an array of objects Genres is an array of strings Friday, December 7, 12
  • 28. CRUD Operations Create, Read, Update and Destroy Data Friday, December 7, 12
  • 29. Mongo CRUD Create is called insert Read is called find Update is called update Destroy is called remove Friday, December 7, 12
  • 30. Mongo CRUD From a developer’s perspective, MongoDB operations are the same through the driver and through the console In both cases, operations look like function calls or method invocations We’ll use mongo shell for the rest of this chapter Friday, December 7, 12
  • 31. Inserting Data Use the command insert or save to insert a new object db.collection.insert( obj ); db.collection.insert( array ); Friday, December 7, 12
  • 32. Inserting Data Inserting to a new collection creates the collection Inserting an object with an _id key, it is used as the object’s id (and must be unique). Friday, December 7, 12
  • 33. Reading Data find and findOne perform read operations Both take a query find returns a cursor findOne returns an object Optional: Fields to fetch db.collection.find( <query>, <projection> ) Friday, December 7, 12
  • 34. Query Document An empty (or missing) query document returns everything db.collection.find({}) db.collection.find() Friday, December 7, 12
  • 35. Query Document Each key/value pair in the query document imposes a condition on the results (objects that match). db.movies.find({ “genre” : “indie” }); db.books.find({“pages” : { “$gt” : 100 }}); Friday, December 7, 12
  • 36. Query Document Query Object Each key/value pair in the query document imposes a condition on the results (objects that match). db.movies.find({ “genre” : “indie” }); db.books.find({“pages” : { “$gt” : 100 }}); Friday, December 7, 12
  • 37. Query Document A compound query means a logical AND on the conditions. db.inventory.find( { “type” : “snacks”, “available” : { “$lt” : 10 } }); Friday, December 7, 12
  • 38. Quiz: What Is Returned from alterego publisher Bruce { Earth DC Wayne “publisher” : “DC” } Peter Earth Marvel Parker Krypton Clark Kent DC Friday, December 7, 12
  • 39. Quiz: What Is Returned from alterego publisher { Bruce “publisher” : Earth DC Wayne “DC”, “from” : “Earth” Peter Earth Marvel } Parker Krypton Clark Kent DC Friday, December 7, 12
  • 40. More Queries You can use “$or” to have an OR expression { “$or” : [ { “type” : “food” }, { “type” : “drinks” } ] } Friday, December 7, 12
  • 41. Sub Documents If your document has sub-documents, it’s possible to query by a full sub document or look for a partial match Full sub-document query means subdocument is exactly as specified in the query Example: { ISBN : { “ISBN-10” : “1906465592”, “ISBN-13” : “978-1906465599” }} Friday, December 7, 12
  • 42. Sub Documents A partial query matches all objects that have at least the required field (but may contain more) Example: { “language.primary” : “english” } Value of language is an object, and it has a field called primary Friday, December 7, 12
  • 43. Arrays You can use an exact array match by providing the full array in the query Example: { tags : [ “funny”, “cute”, “cats” ] } Friday, December 7, 12
  • 44. Arrays You can query for an array that has at least one element matching the query Example: { “tags” : “funny” } Friday, December 7, 12
  • 45. Arrays If you have a subdocument as the element of an array, it’s possible to query by its fields using the dot notation. Examples: { “tracks.4.name” : “Rose Mary Stretch” } { “tracks.name” : “Rose Mary Stretch” } Friday, December 7, 12
  • 46. Query Operators Complex queries are performed with special operators. These are reserved words starting with a $ Some of them: $gt, $gte, $lt, $lte, $ne, $in, $nin, $all, $or, $not Friday, December 7, 12
  • 47. Comparator Queries Value for key a is greater than 10 { “a” : { “$gt” : 10 }} Value for key b is not 7 { “b” : { “$ne” : 7 }} Value for key name is greater (ascii-wise) than ‘bird’ { “name” : { “$gt” : “bird” }} Friday, December 7, 12
  • 48. Queries: $in, $nin Use $in to specify a choice from multiple options Value for grade is 85, 90 or 100 { “grade” : { “$in” : [ 85, 90, 100 ] } } Value for fruit is neither apple nor banana { “fruit” : { “$nin” : [“apple”, “banana” ] } } Friday, December 7, 12
  • 49. Quiz: What Is Selected { “reads” : { “$gt” : 10 }, “author” : { “$nin” : [“admin”, “manager”, “boss” ] } } author reads title How To Use admin 99 Mongo How To Make Joe 120 Money Windows Jim 8 Manual Friday, December 7, 12
  • 50. Queries: $all Select objects with array containing all elements Example: { “tags” : { “$all” : [ “funny”, “cats” ] } } Friday, December 7, 12
  • 51. More Query Operators “$size” - array has a specific number of elements “$exists” - field present or missing Example: { “friends” : { “$size” : 7 } } { “producer” : { “$exists” : false } } Friday, December 7, 12
  • 52. Aggregation count() - returns how many objects found distinct() - returns all distinct values for a key Example: db.posts.distinct( “tags” ) Friday, December 7, 12
  • 53. Resources Queries Cheat Sheet http://www.10gen.com/sites/default/files/downloads/ mongodb_qrc_queries.pdf Friday, December 7, 12
  • 55. Lab Using the previously defined musical DB. Query for: Albums released after/before 2008 Albums with 7 tracks Albums by a specific genre Albums by a specific track name Display ALL different genres in the DB Friday, December 7, 12
  • 56. Update Update operations modify existing data in the DB Mongo supports two update commands: update() and save() Update is the more general (and complex) Friday, December 7, 12
  • 57. Update The general form for update is: db.collection.update( <query>, <update>, <options> ) Which Entries What to do with to update them Friday, December 7, 12
  • 58. Update The second argument to update() is an operator object It tells update what to do with the data Some keys you can use: “$set”, “$inc” “$push”, “$pushAll”, “$addToSet”, “$pop”, “$pull”, “$pullAll” Friday, December 7, 12
  • 59. Update: set $set modifies a value or add a new value Example: db.posts.update( { title: “Why Is Your Cat Unhappy” }, { $set : { “archived” : true } } ); Friday, December 7, 12
  • 60. Quiz: $set What happens here ? db.cats.update( { color: “white” }, { “$set” : { “owners” : [“John”, “Jim”] } } ); Friday, December 7, 12
  • 61. Quiz: $set Update owners array of the first cat with white color If you want to update all objects, use multi db.cats.update( { color: “white” }, { “$set” : { “owners” : [“John”, “Jim”] } } { multi : true } ); Friday, December 7, 12
  • 62. Update: inc $inc increases a numeric value Example: { “$inc” : { “age” : 11 } } Friday, December 7, 12
  • 63. Quiz: $inc What happens here ? db.songs.update( { “title” : “Killing Lies” }, { “$inc” : { “plays” : 1 } } ); Friday, December 7, 12
  • 64. Update: push and pushAll push() and pushAll() add items to an existing array If they array did not exists, it is created Example: db.creatures.update( { name: “The Doctor” }, { “$push” : { companions : “Rose Tyler” } } ) Friday, December 7, 12
  • 65. Update: addToSet The $addToSet adds a new item only if it wasn’t already in the array Example: { “$addToSet” : { “tags” : “funny” } } Friday, December 7, 12
  • 66. Update: pop pop removes items of an array Use a value of 1 to remove the last element Use a value of -1 to remove the first element Example: { “$pop” : { “companions” : 1 } } Friday, December 7, 12
  • 67. Update: pull Remove a specific item from an array. Can use $pullAll to remove all matching elements Example: { “$pull” : { “companions” : “Rose Tyler” } } Friday, December 7, 12
  • 68. Updating with save() The second update operation is save() takes a document: If the document has an id - update it If not, insert it to the DB Friday, December 7, 12
  • 69. Deleting Data remove() deletes objects from a collection Takes a query and possibly a <justOne> arguments Examples: db.posts.remove({ “author” : “Father Angelo” }) db.music.remove({ “genres” : “pop” }) db.posts.remove({ “tags” : “funny” }, 1 ); Friday, December 7, 12
  • 71. Lab From the previous music database: Add a new album with 4 tracks Add a new track to that new album Set property “plays” on all albums to 6 Increase it by 4 only for “indie” albums Delete all “indie” music Friday, December 7, 12
  • 72. Thank You Photos from: http://123rf.com Slides available at: http://ynonperek.com Friday, December 7, 12