SlideShare une entreprise Scribd logo
1  sur  18
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

Tendances (20)

Symbolic Execution And KLEE
Symbolic Execution And KLEESymbolic Execution And KLEE
Symbolic Execution And KLEE
 
Kotlin as a Better Java
Kotlin as a Better JavaKotlin as a Better Java
Kotlin as a Better Java
 
Chapter 02 php basic syntax
Chapter 02   php basic syntaxChapter 02   php basic syntax
Chapter 02 php basic syntax
 
android menus
android menusandroid menus
android menus
 
Kotlin InDepth Tutorial for beginners 2022
Kotlin InDepth Tutorial for beginners 2022Kotlin InDepth Tutorial for beginners 2022
Kotlin InDepth Tutorial for beginners 2022
 
Generics
GenericsGenerics
Generics
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
L11 array list
L11 array listL11 array list
L11 array list
 
MongoDB Aggregation Framework
MongoDB Aggregation FrameworkMongoDB Aggregation Framework
MongoDB Aggregation Framework
 
An Introduction to Python Concurrency
An Introduction to Python ConcurrencyAn Introduction to Python Concurrency
An Introduction to Python Concurrency
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6
 
OpenGL SC 2.0 Quick Reference
OpenGL SC 2.0 Quick ReferenceOpenGL SC 2.0 Quick Reference
OpenGL SC 2.0 Quick Reference
 
MongoDB World 2019: The Sights (and Smells) of a Bad Query
MongoDB World 2019: The Sights (and Smells) of a Bad QueryMongoDB World 2019: The Sights (and Smells) of a Bad Query
MongoDB World 2019: The Sights (and Smells) of a Bad Query
 
Telephony API
Telephony APITelephony API
Telephony API
 
Java String
Java String Java String
Java String
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Discover Quarkus and GraalVM
Discover Quarkus and GraalVMDiscover Quarkus and GraalVM
Discover Quarkus and GraalVM
 
Android Threading
Android ThreadingAndroid Threading
Android Threading
 
Jetpack Compose - Android’s modern toolkit for building native UI
Jetpack Compose - Android’s modern toolkit for building native UIJetpack Compose - Android’s modern toolkit for building native UI
Jetpack Compose - Android’s modern toolkit for building native UI
 
Introduction to flutter
Introduction to flutter Introduction to flutter
Introduction to flutter
 

Similaire à Mastering the MongoDB 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
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
Alex Bilbie
 

Similaire à Mastering the MongoDB Shell (20)

Mongophilly shell-2011-04-26
Mongophilly shell-2011-04-26Mongophilly shell-2011-04-26
Mongophilly shell-2011-04-26
 
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
 
Latinoware
LatinowareLatinoware
Latinoware
 
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
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
RubyEnRails2007 - Dr Nic Williams - Keynote
RubyEnRails2007 - Dr Nic Williams - KeynoteRubyEnRails2007 - Dr Nic Williams - Keynote
RubyEnRails2007 - Dr Nic Williams - Keynote
 

Plus de MongoDB

Plus 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...
 

Dernier

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
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Dernier (20)

Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
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
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
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
 
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
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
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...
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
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
 
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
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 

Mastering the MongoDB 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