SlideShare a Scribd company logo
1 of 44
Download to read offline
MongoDB For Perl
                      Developers
                      { author: “Ynon Perek” }




Friday, March 1, 13
Whoami




                      Ynon Perek

                      http://ynonperek.com

                      ynon@ynonperek.com




Friday, March 1, 13
Agenda



                           Mongo Is Awesome

                           CRUD Operations

                           The Driver

                           Coding Time




Friday, March 1, 13
Mongo Is Awesome



                      Data Store for
                      JSON Objects




Friday, March 1, 13
Mongo Is Awesome



                      Data Store for
                      JSON Objects


          {
                “Name” : “Rose Tyler”
          }




Friday, March 1, 13
JSON Objects


                      A JSON Object is a
                      collection of key/
                      value pairs          {
                                             "name"       : "Rose Tyler",
                      Keys are simple        "race"       : "Human",
                      strings                "body parts" : [ "head", "legs"]
                                           }
                      Values can be:
                      Numbers, Strings,
                      Arrays, Other
                      Objects, and more




Friday, March 1, 13
It’s A Document Oriented Data
                      Store




Friday, March 1, 13
It don’t do joins




Friday, March 1, 13
It don’t do transactions




Friday, March 1, 13
Keeping It Simple




                      Document Oriented

                      No Transactions

                      No Joins




Friday, March 1, 13
Application Architecture




                        APP            DB




Friday, March 1, 13
What Can Mongo Do For You




                      Create and store objects

                      Arrange them in collections

                      Retrieve them later




Friday, March 1, 13
Q&A




Friday, March 1, 13
CRUD Operations
                      Create, Read, Update and Destroy Data


Friday, March 1, 13
Mongo CRUD



                      Create   is called insert

                      Read     is called find

                      Update is called update

                      Destroy is called remove




Friday, March 1, 13
Mongo CRUD


                      db.highscore.insert ({"name":"Tom", "score":94});

                      db.highscore.find   ({"name" : "Tom" })

                      db.highscore.update ({"name" : "Tom"},
                                           {"$inc" : { "score" : 1 } });

                      db.highscore.remove ({"name" : "Tom"});




Friday, March 1, 13
Inserting Data




                      Use the command insert or save to insert a new object

                      db.collection.insert( obj );

                      db.collection.insert( array );




Friday, March 1, 13
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, March 1, 13
Demo: Insert




Friday, March 1, 13
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, March 1, 13
Query Document



                      An empty (or missing) query document returns
                      everything

                      db.collection.find({})

                      db.collection.find()




Friday, March 1, 13
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, March 1, 13
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, March 1, 13
Query Document


                      A compound query means a logical AND on the
                      conditions.

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




Friday, March 1, 13
Quiz: What Is Returned


                                          from      alterego   publisher

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

                                          Krypton   Clark Kent DC



Friday, March 1, 13
Quiz: What Is Returned


                                          from      alterego   publisher

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

                                          Krypton   Clark Kent DC



Friday, March 1, 13
Resources




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




Friday, March 1, 13
Demo: Query




Friday, March 1, 13
Update




                      The general form for update is:


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



               Which Entries                   What to do with
               to update                       them

Friday, March 1, 13
Update



                      Some Update Operators

                        “$set”, “$inc”

                        “$push”, “$pushAll”, “$addToSet”

                        “$pop”, “$pull”, “$pullAll”




Friday, March 1, 13
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, March 1, 13
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, March 1, 13
Deleting Data



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

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

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




Friday, March 1, 13
Q&A




Friday, March 1, 13
The Driver



                      Hello MongoDB

                      Connecting and Authenticating

                      Querying/Updating Data

                      Coding Time




Friday, March 1, 13
Hello MongoDB



                      Mike Friedman, Kristina
                      Chodorow and rafl

                      MongoDB::Examples

                      MongoDB::Tutorial

                      Alternative Driver:
                      Mango




Friday, March 1, 13
Hello Mongo

              use strict;
              use warnings;
              use v5.14;
              use MongoDB;
              use Data::Printer;
               
              my $client = MongoDB::MongoClient->new;
              my $db = $client->get_database('demo');
               
              my $coll = $db->get_collection('highscore');
              my @objects = $coll->find->all;
               
              p @objects;




Friday, March 1, 13
Inserting Data

              use strict;
              use warnings;
              use v5.14;
              use MongoDB;
               
              my $client = MongoDB::MongoClient->new;
              my $db = $client->get_database('demo');
               
              my $coll = $db->get_collection('highscore');
               
              $coll->insert({ name => 'Mike', score => 99 });




Friday, March 1, 13
Querying Data



              my $cursor = $coll->find({name => 'Tom'});
               
              while ( my $next = $cursor->next ) {
                say $next->{name}, " Got: ", $next->{score};
              }




Friday, March 1, 13
Querying Data

                      Sort, Limit and Skip results using the cursor

              my $cursor = $coll->find()->
                              sort({score => -1})->
                              limit(3);
               
              while ( my $next = $cursor->next ) {
                say $next->{name}, " Got: ", $next->{score};
              }




Friday, March 1, 13
Update Data


                      $coll->update( { name => 'Tom' },
                                     { '$inc' => { score => 1 } } );



                      $coll->update( { name => 'Tom' },
                                     { '$inc' => { score => 1 } },
                                     { multiple => 1 } );




Friday, March 1, 13
Deleting Data


               
              my $client = MongoDB::MongoClient->new;
              my $db = $client->get_database('demo');
               
              my $coll = $db->get_collection('highscore');
               
              $coll->remove( { score => { '$gt' => 80 } } );




Friday, March 1, 13
Coding Time


                      Mongo Log Parsing

                      Mongo Web Address
                      Book

                      Code Examples At:
                      https://github.com/
                      ynonp/perl-
                      workshop-2013




Friday, March 1, 13
Thanks For Listening



                      Ynon Perek

                      Slides at:
                      ynonperek.com

                      Talk to me at:
                      ynon@ynonperek.com




Friday, March 1, 13

More Related Content

More from 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
 

More from 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
 

Recently uploaded

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 

Recently uploaded (20)

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

MongoDB for Perl Developers

  • 1. MongoDB For Perl Developers { author: “Ynon Perek” } Friday, March 1, 13
  • 2. Whoami Ynon Perek http://ynonperek.com ynon@ynonperek.com Friday, March 1, 13
  • 3. Agenda Mongo Is Awesome CRUD Operations The Driver Coding Time Friday, March 1, 13
  • 4. Mongo Is Awesome Data Store for JSON Objects Friday, March 1, 13
  • 5. Mongo Is Awesome Data Store for JSON Objects { “Name” : “Rose Tyler” } Friday, March 1, 13
  • 6. JSON Objects A JSON Object is a collection of key/ value pairs {   "name" : "Rose Tyler", Keys are simple   "race" : "Human", strings   "body parts" : [ "head", "legs"] } Values can be: Numbers, Strings, Arrays, Other Objects, and more Friday, March 1, 13
  • 7. It’s A Document Oriented Data Store Friday, March 1, 13
  • 8. It don’t do joins Friday, March 1, 13
  • 9. It don’t do transactions Friday, March 1, 13
  • 10. Keeping It Simple Document Oriented No Transactions No Joins Friday, March 1, 13
  • 11. Application Architecture APP DB Friday, March 1, 13
  • 12. What Can Mongo Do For You Create and store objects Arrange them in collections Retrieve them later Friday, March 1, 13
  • 14. CRUD Operations Create, Read, Update and Destroy Data Friday, March 1, 13
  • 15. Mongo CRUD Create is called insert Read is called find Update is called update Destroy is called remove Friday, March 1, 13
  • 16. Mongo CRUD db.highscore.insert ({"name":"Tom", "score":94}); db.highscore.find ({"name" : "Tom" }) db.highscore.update ({"name" : "Tom"}, {"$inc" : { "score" : 1 } }); db.highscore.remove ({"name" : "Tom"}); Friday, March 1, 13
  • 17. Inserting Data Use the command insert or save to insert a new object db.collection.insert( obj ); db.collection.insert( array ); Friday, March 1, 13
  • 18. 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, March 1, 13
  • 20. 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, March 1, 13
  • 21. Query Document An empty (or missing) query document returns everything db.collection.find({}) db.collection.find() Friday, March 1, 13
  • 22. 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, March 1, 13
  • 23. 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, March 1, 13
  • 24. Query Document A compound query means a logical AND on the conditions. db.inventory.find(  {     “type” : “snacks”,     “available” : { “$lt” : 10 }  }); Friday, March 1, 13
  • 25. Quiz: What Is Returned from alterego publisher Bruce { Earth DC Wayne “publisher” : “DC” } Peter Earth Marvel Parker Krypton Clark Kent DC Friday, March 1, 13
  • 26. Quiz: What Is Returned from alterego publisher { Bruce “publisher” : Earth DC Wayne “DC”, “from” : “Earth” Peter Earth Marvel } Parker Krypton Clark Kent DC Friday, March 1, 13
  • 27. Resources Queries Cheat Sheet http://www.10gen.com/sites/default/files/downloads/ mongodb_qrc_queries.pdf Friday, March 1, 13
  • 29. Update The general form for update is: db.collection.update( <query>, <update>, <options> ) Which Entries What to do with to update them Friday, March 1, 13
  • 30. Update Some Update Operators “$set”, “$inc” “$push”, “$pushAll”, “$addToSet” “$pop”, “$pull”, “$pullAll” Friday, March 1, 13
  • 31. 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, March 1, 13
  • 32. 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, March 1, 13
  • 33. Deleting Data db.posts.remove( { “author” : “Father Angelo” }) db.music.remove({ “genres” : “pop” }) db.posts.remove({ “tags” : “funny” }, 1); Friday, March 1, 13
  • 35. The Driver Hello MongoDB Connecting and Authenticating Querying/Updating Data Coding Time Friday, March 1, 13
  • 36. Hello MongoDB Mike Friedman, Kristina Chodorow and rafl MongoDB::Examples MongoDB::Tutorial Alternative Driver: Mango Friday, March 1, 13
  • 37. Hello Mongo use strict; use warnings; use v5.14; use MongoDB; use Data::Printer;   my $client = MongoDB::MongoClient->new; my $db = $client->get_database('demo');   my $coll = $db->get_collection('highscore'); my @objects = $coll->find->all;   p @objects; Friday, March 1, 13
  • 38. Inserting Data use strict; use warnings; use v5.14; use MongoDB;   my $client = MongoDB::MongoClient->new; my $db = $client->get_database('demo');   my $coll = $db->get_collection('highscore');   $coll->insert({ name => 'Mike', score => 99 }); Friday, March 1, 13
  • 39. Querying Data my $cursor = $coll->find({name => 'Tom'});   while ( my $next = $cursor->next ) {   say $next->{name}, " Got: ", $next->{score}; } Friday, March 1, 13
  • 40. Querying Data Sort, Limit and Skip results using the cursor my $cursor = $coll->find()-> sort({score => -1})-> limit(3);   while ( my $next = $cursor->next ) {   say $next->{name}, " Got: ", $next->{score}; } Friday, March 1, 13
  • 41. Update Data $coll->update( { name => 'Tom' }, { '$inc' => { score => 1 } } ); $coll->update( { name => 'Tom' }, { '$inc' => { score => 1 } }, { multiple => 1 } ); Friday, March 1, 13
  • 42. Deleting Data   my $client = MongoDB::MongoClient->new; my $db = $client->get_database('demo');   my $coll = $db->get_collection('highscore');   $coll->remove( { score => { '$gt' => 80 } } ); Friday, March 1, 13
  • 43. Coding Time Mongo Log Parsing Mongo Web Address Book Code Examples At: https://github.com/ ynonp/perl- workshop-2013 Friday, March 1, 13
  • 44. Thanks For Listening Ynon Perek Slides at: ynonperek.com Talk to me at: ynon@ynonperek.com Friday, March 1, 13