SlideShare uma empresa Scribd logo
1 de 18
Baixar para ler offline
Mastering the Shell — MongoBerlin

                                    Richard M Kreuter
                                         10gen Inc.
                                    richard@10gen.com


                                     March 25, 2011




Mastering the Shell — MongoBerlin
The Mongo Shell




  What is the shell?
  The mongo shell is a JavaScript interpreter with built-in support for
  MongoDB connectivity.




  Mastering the Shell — MongoBerlin
What’s the shell good for?




          Interactive development/prototyping.
          Test scripting (cf. MongoDB’s own regression framework).
          Administrative operations, lightweight scripting.
          Learning MongoDB (and teaching it, too).




   Mastering the Shell — MongoBerlin
Running the Shell




   $ mongo
   MongoDB shell version: 1.6.4
   connecting to: test
   > db.people.save({name:"Washington", no: 1});
   > db.people.save({name:"Adams", no: 2});
   > db.people.save({name:"Jefferson", no: 3});
   > for (i=0; i<1024; i++) db.numbers.save({ num: i });




   Mastering the Shell — MongoBerlin
Running the shell (continued)



   You can execute a file of code either by specifying command-line
   argument or with the built-in load extension function.

   $ mongo foo.js # executes foo.js and exits
   $ mongo
   MongoDB shell version: 1.6.4
   connecting to: test
   > load("foo.js") // executes foo.js and returns to prompt




   Mastering the Shell — MongoBerlin
Running the shell (continued continued)




   As of 1.8, you can also use mongo as a “shebang” interpreter.

   $ cat ~/foo.js
   #!/Users/kreuter/10gen/mongo/mongo

   ...
   $ ./foo.js




   Mastering the Shell — MongoBerlin
Shell helpers


   The shell has some built-in helpers that resemble the MySQL
   shell’s.

   // Change database to "foo"
   use foo
   // List the collections in "foo"
   show collections

   Note that these helpers aren’t strictly JavaScript; they’re sort of
   preprocessors available only when the shell is run interactively.
   There are proper JavaScript methods for doing these things
   programmatically (e.g., db=db.getSisterDB("foo")).



   Mastering the Shell — MongoBerlin
Completion in interactive mode



   The shell supports completion (improved notably in 1.8).
   Completion can introspect on JavaScript objects to find
   attributes/methods:

   db.<TAB> // print methods on the db object
   db.people.<TAB> // print methods on the people collection
   // etc...




   Mastering the Shell — MongoBerlin
Command-line editing




   The shell uses readline for command completion, history, editing,
   etc. (for now, anyway). So it has similar keybindings by default to
   those in bash, et. al.




   Mastering the Shell — MongoBerlin
Getting help




   > help // help is a helper...
   ...
   > db.help() // db.help() is a method on the db object
   ...
   > db.collection.help() // a method on the collection




   Mastering the Shell — MongoBerlin
Working with the shell



   The shell runs all queries in “SafeMode”, i.e., it executes
   getLastError and prints any error message after data
   manipulations. So, for example,

   > db.foo.insert({_id:1});
   > db.foo.insert({_id:1});
   E11000 duplicate key error index: test.foo.$_id_
     dup key: { : 1.0 }




   Mastering the Shell — MongoBerlin
Working with the shell (continued)


   Because the shell uses JavaScript, a little care is called for when
   handling types MongoDB supports that JavaScript doesn’t:
          JavaScript’s only number type is double-floats. (Use
          NumberLong to construct 64-bit integers.)
          Documents having multiple values for the same key aren’t
          supported in JavaScript (but you shouldn’t really use these
          anyway).
          Binary data is represented by the BinData type.
          Also, note that in JavaScript, Date(string) returns a string;
          you almost always want new Date(string), which returns an
          object. (In 1.8, see the ISODate() function.)



   Mastering the Shell — MongoBerlin
Cursors in the shell


   By default, cursors in the shell are printed by iterating the cursor
   some number of times, and assigning the variable it to an iterator:

   > db.numbers.find()
   { "_id" : ObjectId("4cf91b32e3f85d1561593dfc"), "num" : 0 }
   ...
   has more
   > it
   { "_id" : ObjectId("4cf91b32e3f85d1561593e10"), "num" : 20
   ...
   has more




   Mastering the Shell — MongoBerlin
Cursors in the shell (continued)

   The shell supports cursors as first-class objects:

   > var cur=db.people.find()
   > cur.hasNext()
   true
   > while (cur.hasNext()) { printjson(cur.next().name); }
   "Washington"
   "Adams"
   "Jefferson"
   > var cur2=db.people.find({}, {name:1})
   > cur2.forEach(printjson)
   { "_id" : ..., "name" : "Washington" }
   { "_id" : ..., "name" : "Adams" }
   { "_id" : ..., "name" : "Jefferson" }


   Mastering the Shell — MongoBerlin
Examining JavaScript code
   Most of the shell’s functionality is implemented in JavaScript itself,
   with the consequence that you can examine (and so cargo-cult) it
   yourself:
   > db.people.findOne
   function (query, fields) {
       var cursor = this._mongo.find(this._fullName,
         this._massageObject(query) || {}, fields, -1, 0, 0);
       if (!cursor.hasNext())
           return null;
       var ret = cursor.next();
       if (cursor.hasNext())
           throw "findOne has more than 1 result!";
       if (ret.$err)
           throw "error " + tojson(ret);
       return ret;
   }
   Mastering the Shell — MongoBerlin
A nifty function


   Here’s a nifty administrative function (stolen from Scott
   Hernandez’s talk on the shell):

   var cursor = db.coll.find();
   var biggest=0;
   var doc = {};
   cursor.forEach(function (x) {
           var size = Object.bsonsize(x);
           if (size > biggest) { biggest=size; doc = x; }
   });




   Mastering the Shell — MongoBerlin
Gotchas




         JavaScript isn’t the fastest language around.
         JavaScript lacks features for “programming in the large”
         (modules/packages/namespaces/etc.)
         Iterating arrays (in index order) is slow.
         Some data types require special care.




  Mastering the Shell — MongoBerlin
So give the shell another spin!



          www.mongodb.org — downloads, docs, community
          mongodb-user@googlegroups.com — mailing list
          #mongodb on irc.freenode.net
          try.mongodb.org — web-based shell
          10gen is hiring. Email jobs@10gen.com.
          10gen offers support, training, and advising services for
          mongodb




   Mastering the Shell — MongoBerlin

Mais conteúdo relacionado

Mais procurados

Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
Alex Bilbie
 
C# Development (Sam Corder)
C# Development (Sam Corder)C# Development (Sam Corder)
C# Development (Sam Corder)
MongoSF
 
Java Development with MongoDB
Java Development with MongoDBJava Development with MongoDB
Java Development with MongoDB
Scott Hernandez
 
MongoDB Aug2010 SF Meetup
MongoDB Aug2010 SF MeetupMongoDB Aug2010 SF Meetup
MongoDB Aug2010 SF Meetup
Scott Hernandez
 
Terrastore - A document database for developers
Terrastore - A document database for developersTerrastore - A document database for developers
Terrastore - A document database for developers
Sergio Bossa
 

Mais procurados (20)

Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
Indexing
IndexingIndexing
Indexing
 
C# Development (Sam Corder)
C# Development (Sam Corder)C# Development (Sam Corder)
C# Development (Sam Corder)
 
Streams in Node.js
Streams in Node.jsStreams in Node.js
Streams in Node.js
 
File input output in Java
File input output in JavaFile input output in Java
File input output in Java
 
MongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with MorphiaMongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with Morphia
 
Java Development with MongoDB
Java Development with MongoDBJava Development with MongoDB
Java Development with MongoDB
 
Thinking in Sequences - Streams in Node.js & IO.js
Thinking in Sequences - Streams in Node.js & IO.jsThinking in Sequences - Streams in Node.js & IO.js
Thinking in Sequences - Streams in Node.js & IO.js
 
Learn JS concepts by implementing jQuery
Learn JS concepts by implementing jQueryLearn JS concepts by implementing jQuery
Learn JS concepts by implementing jQuery
 
Python Files
Python FilesPython Files
Python Files
 
Mysql to mongo
Mysql to mongoMysql to mongo
Mysql to mongo
 
JavaScript Looping Statements
JavaScript Looping StatementsJavaScript Looping Statements
JavaScript Looping Statements
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
 
React.js 20150828
React.js 20150828React.js 20150828
React.js 20150828
 
JavaScript Language Paradigms
JavaScript Language ParadigmsJavaScript Language Paradigms
JavaScript Language Paradigms
 
MongoDB-SESSION03
MongoDB-SESSION03MongoDB-SESSION03
MongoDB-SESSION03
 
Introduction to JRuby
Introduction to JRubyIntroduction to JRuby
Introduction to JRuby
 
MongoDB Aug2010 SF Meetup
MongoDB Aug2010 SF MeetupMongoDB Aug2010 SF Meetup
MongoDB Aug2010 SF Meetup
 
Terrastore - A document database for developers
Terrastore - A document database for developersTerrastore - A document database for developers
Terrastore - A document database for developers
 
Data Modeling for the Real World
Data Modeling for the Real WorldData Modeling for the Real World
Data Modeling for the Real World
 

Destaque (7)

Schema Design
Schema DesignSchema Design
Schema Design
 
Modeling for Performance
Modeling for PerformanceModeling for Performance
Modeling for Performance
 
2011 mongo sf-sharding
2011 mongo sf-sharding2011 mongo sf-sharding
2011 mongo sf-sharding
 
Keeping data-safe-webinar-2010-11-01
Keeping data-safe-webinar-2010-11-01Keeping data-safe-webinar-2010-11-01
Keeping data-safe-webinar-2010-11-01
 
Morning with MongoDB Paris 2012 - Making Big Data Small
Morning with MongoDB Paris 2012 - Making Big Data SmallMorning with MongoDB Paris 2012 - Making Big Data Small
Morning with MongoDB Paris 2012 - Making Big Data Small
 
Securing Data in MongoDB with Gazzang and Chef
Securing Data in MongoDB with Gazzang and ChefSecuring Data in MongoDB with Gazzang and Chef
Securing Data in MongoDB with Gazzang and Chef
 
Indexing and Query Optimizer (Richard Kreuter)
Indexing and Query Optimizer (Richard Kreuter)Indexing and Query Optimizer (Richard Kreuter)
Indexing and Query Optimizer (Richard Kreuter)
 

Semelhante a Mongo Berlin - Mastering the Shell

Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
intelliyole
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends
旻琦 潘
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
FrozenRails Training
FrozenRails TrainingFrozenRails Training
FrozenRails Training
Mike Dirolf
 
MongoDB Shell Tips & Tricks
MongoDB Shell Tips & TricksMongoDB Shell Tips & Tricks
MongoDB Shell Tips & Tricks
MongoDB
 

Semelhante a Mongo Berlin - Mastering the Shell (20)

JRuby e DSL
JRuby e DSLJRuby e DSL
JRuby e DSL
 
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
 
Week3
Week3Week3
Week3
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
 
[FT-7][snowmantw] How to make a new functional language and make the world be...
[FT-7][snowmantw] How to make a new functional language and make the world be...[FT-7][snowmantw] How to make a new functional language and make the world be...
[FT-7][snowmantw] How to make a new functional language and make the world be...
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
 
JavaScript Miller Columns
JavaScript Miller ColumnsJavaScript Miller Columns
JavaScript Miller Columns
 
MongoDB
MongoDBMongoDB
MongoDB
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
jsbasics-slide
jsbasics-slidejsbasics-slide
jsbasics-slide
 
FrozenRails Training
FrozenRails TrainingFrozenRails Training
FrozenRails Training
 
All of Javascript
All of JavascriptAll of Javascript
All of Javascript
 
Mongoose and MongoDB 101
Mongoose and MongoDB 101Mongoose and MongoDB 101
Mongoose and MongoDB 101
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with Clojure
 
RubyEnRails2007 - Dr Nic Williams - Keynote
RubyEnRails2007 - Dr Nic Williams - KeynoteRubyEnRails2007 - Dr Nic Williams - Keynote
RubyEnRails2007 - Dr Nic Williams - Keynote
 
MongoDB Shell Tips & Tricks
MongoDB Shell Tips & TricksMongoDB Shell Tips & Tricks
MongoDB Shell Tips & Tricks
 
Survive JavaScript - Strategies and Tricks
Survive JavaScript - Strategies and TricksSurvive JavaScript - Strategies and Tricks
Survive JavaScript - Strategies and Tricks
 
Global objects in Node.pdf
Global objects in Node.pdfGlobal objects in Node.pdf
Global objects in Node.pdf
 

Mais de MongoDB

Mais de MongoDB (20)

MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB SoCal 2020: Migrate Anything* to MongoDB AtlasMongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
 
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!
 
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...
 
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDB
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDBMongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDB
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDB
 
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...
 
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series Data
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series DataMongoDB SoCal 2020: Best Practices for Working with IoT and Time-series Data
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series Data
 
MongoDB SoCal 2020: MongoDB Atlas Jump Start
 MongoDB SoCal 2020: MongoDB Atlas Jump Start MongoDB SoCal 2020: MongoDB Atlas Jump Start
MongoDB SoCal 2020: MongoDB Atlas Jump Start
 
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
 
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
 
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
 
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
 
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your MindsetMongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
 
MongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
MongoDB .local San Francisco 2020: MongoDB Atlas JumpstartMongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
MongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
 
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
 
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
 
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
 
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep DiveMongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
 
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & GolangMongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
 
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
 
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...
 

Último

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
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...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 

Mongo Berlin - Mastering the Shell

  • 1. Mastering the Shell — MongoBerlin Richard M Kreuter 10gen Inc. richard@10gen.com March 25, 2011 Mastering the Shell — MongoBerlin
  • 2. The Mongo Shell What is the shell? The mongo shell is a JavaScript interpreter with built-in support for MongoDB connectivity. Mastering the Shell — MongoBerlin
  • 3. What’s the shell good for? Interactive development/prototyping. Test scripting (cf. MongoDB’s own regression framework). Administrative operations, lightweight scripting. Learning MongoDB (and teaching it, too). Mastering the Shell — MongoBerlin
  • 4. Running the Shell $ mongo MongoDB shell version: 1.6.4 connecting to: test > db.people.save({name:"Washington", no: 1}); > db.people.save({name:"Adams", no: 2}); > db.people.save({name:"Jefferson", no: 3}); > for (i=0; i<1024; i++) db.numbers.save({ num: i }); Mastering the Shell — MongoBerlin
  • 5. Running the shell (continued) You can execute a file of code either by specifying command-line argument or with the built-in load extension function. $ mongo foo.js # executes foo.js and exits $ mongo MongoDB shell version: 1.6.4 connecting to: test > load("foo.js") // executes foo.js and returns to prompt Mastering the Shell — MongoBerlin
  • 6. Running the shell (continued continued) As of 1.8, you can also use mongo as a “shebang” interpreter. $ cat ~/foo.js #!/Users/kreuter/10gen/mongo/mongo ... $ ./foo.js Mastering the Shell — MongoBerlin
  • 7. Shell helpers The shell has some built-in helpers that resemble the MySQL shell’s. // Change database to "foo" use foo // List the collections in "foo" show collections Note that these helpers aren’t strictly JavaScript; they’re sort of preprocessors available only when the shell is run interactively. There are proper JavaScript methods for doing these things programmatically (e.g., db=db.getSisterDB("foo")). Mastering the Shell — MongoBerlin
  • 8. Completion in interactive mode The shell supports completion (improved notably in 1.8). Completion can introspect on JavaScript objects to find attributes/methods: db.<TAB> // print methods on the db object db.people.<TAB> // print methods on the people collection // etc... Mastering the Shell — MongoBerlin
  • 9. Command-line editing The shell uses readline for command completion, history, editing, etc. (for now, anyway). So it has similar keybindings by default to those in bash, et. al. Mastering the Shell — MongoBerlin
  • 10. Getting help > help // help is a helper... ... > db.help() // db.help() is a method on the db object ... > db.collection.help() // a method on the collection Mastering the Shell — MongoBerlin
  • 11. Working with the shell The shell runs all queries in “SafeMode”, i.e., it executes getLastError and prints any error message after data manipulations. So, for example, > db.foo.insert({_id:1}); > db.foo.insert({_id:1}); E11000 duplicate key error index: test.foo.$_id_ dup key: { : 1.0 } Mastering the Shell — MongoBerlin
  • 12. Working with the shell (continued) Because the shell uses JavaScript, a little care is called for when handling types MongoDB supports that JavaScript doesn’t: JavaScript’s only number type is double-floats. (Use NumberLong to construct 64-bit integers.) Documents having multiple values for the same key aren’t supported in JavaScript (but you shouldn’t really use these anyway). Binary data is represented by the BinData type. Also, note that in JavaScript, Date(string) returns a string; you almost always want new Date(string), which returns an object. (In 1.8, see the ISODate() function.) Mastering the Shell — MongoBerlin
  • 13. Cursors in the shell By default, cursors in the shell are printed by iterating the cursor some number of times, and assigning the variable it to an iterator: > db.numbers.find() { "_id" : ObjectId("4cf91b32e3f85d1561593dfc"), "num" : 0 } ... has more > it { "_id" : ObjectId("4cf91b32e3f85d1561593e10"), "num" : 20 ... has more Mastering the Shell — MongoBerlin
  • 14. Cursors in the shell (continued) The shell supports cursors as first-class objects: > var cur=db.people.find() > cur.hasNext() true > while (cur.hasNext()) { printjson(cur.next().name); } "Washington" "Adams" "Jefferson" > var cur2=db.people.find({}, {name:1}) > cur2.forEach(printjson) { "_id" : ..., "name" : "Washington" } { "_id" : ..., "name" : "Adams" } { "_id" : ..., "name" : "Jefferson" } Mastering the Shell — MongoBerlin
  • 15. Examining JavaScript code Most of the shell’s functionality is implemented in JavaScript itself, with the consequence that you can examine (and so cargo-cult) it yourself: > db.people.findOne function (query, fields) { var cursor = this._mongo.find(this._fullName, this._massageObject(query) || {}, fields, -1, 0, 0); if (!cursor.hasNext()) return null; var ret = cursor.next(); if (cursor.hasNext()) throw "findOne has more than 1 result!"; if (ret.$err) throw "error " + tojson(ret); return ret; } Mastering the Shell — MongoBerlin
  • 16. A nifty function Here’s a nifty administrative function (stolen from Scott Hernandez’s talk on the shell): var cursor = db.coll.find(); var biggest=0; var doc = {}; cursor.forEach(function (x) { var size = Object.bsonsize(x); if (size > biggest) { biggest=size; doc = x; } }); Mastering the Shell — MongoBerlin
  • 17. Gotchas JavaScript isn’t the fastest language around. JavaScript lacks features for “programming in the large” (modules/packages/namespaces/etc.) Iterating arrays (in index order) is slow. Some data types require special care. Mastering the Shell — MongoBerlin
  • 18. So give the shell another spin! www.mongodb.org — downloads, docs, community mongodb-user@googlegroups.com — mailing list #mongodb on irc.freenode.net try.mongodb.org — web-based shell 10gen is hiring. Email jobs@10gen.com. 10gen offers support, training, and advising services for mongodb Mastering the Shell — MongoBerlin