SlideShare ist ein Scribd-Unternehmen logo
1 von 26
Downloaden Sie, um offline zu lesen
#MongoDBDays




MongoDB Shell Tips &
Tricks
Hannes Magnusson
Driver Engineer, 10gen
@bjori
What is the Shell?
  Embedded
                    • vars / functions / data structs + types
  Javascript        • Spidermonkey / V8
  Interpreter
                    • ObjectId("...")
Global Functions    • new Date()
  and Objects       • Object.bsonsize()


MongoDB driver      • db["collection"].find/count/update
   Exposed          • short-hand for collections



                    • Doesn't require quoted keys
JSON-like stuff     • Don’t copy and paste too much


                   Shell Tips & Tricks, Hannes Magnusson
MongoDB Shell: Advantages
• Your goto tool
• Debugging Queries / Syntax
• Testing
• Administration
• Scripting Glue
• You don’t do rs.stepDown() from your application



                   Shell Tips & Tricks, Hannes Magnusson
MongoDB Shell: Disadvantages
• Numbers in JS are a pain
  – 32/64-bit int/long  NumberInt() / NumberLong()
  – Primitive numbers are all 64-bit FP doubles

• Dates can be confusing
  – new Date( "1/1/1" )
  – new ISODate( ... )

          NOT: Date( "1/1/1" )  string




                    Shell Tips & Tricks, Hannes Magnusson
Emacs-like shell bindings
 ctrl A   Move cursor to start of line
 ctrl E   Move cursor to end of line
 meta B   Move cursor left by one word
 meta F   Move cursor right by one word
 ctrl L   Clear screen and redisplay line
 ctrl R   Reverse history search
 meta <   Start of history
 meta >   End of history


              Shell Tips & Tricks, Hannes Magnusson
MongoDB Shell Tips & Tricks
Emacs-like shell bindings
 ctrl A   Move cursor to start of line
 ctrl E   Move cursor to end of line
 meta B   Move cursor left by one word
 meta F   Move cursor right by one word
 ctrl L   Clear screen and redisplay line
 ctrl R   Reverse history search
 meta <   Start of history
 meta >   End of history


              Shell Tips & Tricks, Hannes Magnusson
Easy to use
• Tab completion on most objects
• Built-in help on most objects (.help())
• show
   –   profile # 5 most recent ops of 1ms or more
   –   users # List all the users of the current db
   –   dbs # List all the databases
   –   logs # List all available logs
• Most examples use the shell


                       Shell Tips & Tricks, Hannes Magnusson
Speed Considerations
• Shell
   – JavaScript is slow
   – Always in "write-acknowledged" (safe mode) / GLE
   – Data Conversions

• Server
   – Applies on the server as well
   – Careful with round-tripping numbers




                    Shell Tips & Tricks, Hannes Magnusson
Insert, Update, Remove

for ( i = 0; i < 1000; i++ ) {
  db.test.insert( {
      x: i,
      ts: new Date()
  } );
}


                Shell Tips & Tricks, Hannes Magnusson
Loading Scripts
• Commandline
   – --eval switch
   – .js files

• Within the shell
   – load()




                     Shell Tips & Tricks, Hannes Magnusson
Running Commands
• db.runCommand( { ... } )
   – Runs any arbitrary command against the current DB

• db.adminCommand( { ... } )
   – Run commands against the admin database




                    Shell Tips & Tricks, Hannes Magnusson
db.adminCommand
Definition
function (obj) {
  if (this._name == "admin") {
      return this.runCommand(obj);
  }
  return this.getSiblingDB("admin")
        .runCommand(obj);
}

             Shell Tips & Tricks, Hannes Magnusson
Profiling
• setProfilingLevel( lvl, <ms> )
   – 0: none
   – 1: time-based
   – 2: all

• getProfilingLevel()
• Reading from the profile collection
   – db.system.profile.find()




                      Shell Tips & Tricks, Hannes Magnusson
Cool Functions
• printjson()  tojson
• forEach on arrays, queries, and cursors




                  Shell Tips & Tricks, Hannes Magnusson
You didn’t hear it from me

db.system.js.save({ _id:"echoFunction",
     value : function(x) { return x; }
})
db.loadServerScripts();
echoFunction(3);


              Shell Tips & Tricks, Hannes Magnusson
MongoDB Shell Tips & Tricks
forEach example

[{x:1},{y:1}].forEach(function(x) {
   printjson(x)
})

{ "x" : 1 }
{ "y" : 1 }



              Shell Tips & Tricks, Hannes Magnusson
Cool Functions
• printjson  tojson
• forEach on arrays, queries, and cursors
• Object.bsonsize
• load(file)
• run(file)




                 Shell Tips & Tricks, Hannes Magnusson
Print all Indexes

db.getCollectionNames().
forEach( function(x) {
   print( "Collection: " + x );
   printjson( db[x].getIndexes() );
})




              Shell Tips & Tricks, Hannes Magnusson
Getting the Biggest Doc
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;
  }
});
                Shell Tips & Tricks, Hannes Magnusson
Administration functions
• Sharding
   – sh.status()
   – sh.enableSharding(dbname)

• Replicaset
   – rs.status()
   – cfg = rs.config(); rs.reconfig(cfg);
   – db.isMaster()

• Status
   – Object.bsonsize(document)
   – db.collectionName.stats()

                       Shell Tips & Tricks, Hannes Magnusson
MongoDB Shell Tips & Tricks
.mongorc.js
• Automagically loaded on startup
   – Unless you specify --norc

• Script your command prompt
   – prompt=function() { return "Hello World"; }

• Colorize output
• Move complex aggregate() queries into functions
• Can be a directory



                     Shell Tips & Tricks, Hannes Magnusson
Want to know more?
         The shell is self documented, in JavaScript o/
                            …Except the native helper

• help
   – dbs # Shows all commands you can run on a database
   – connect # Connect to other nodes

• Call a function, without the brackets
   – Will show you the actual code behind it


• try.mongodb.org !


                     Shell Tips & Tricks, Hannes Magnusson
#MongoDBDays




Thank You
Hannes Magnusson
Driver Engineer, 10gen
@bjori

Weitere ähnliche Inhalte

Was ist angesagt?

Parallel Query in AWS Aurora MySQL
Parallel Query in AWS Aurora MySQLParallel Query in AWS Aurora MySQL
Parallel Query in AWS Aurora MySQLMydbops
 
Get to Green: How to Safely Refactor Legacy Code
Get to Green: How to Safely Refactor Legacy CodeGet to Green: How to Safely Refactor Legacy Code
Get to Green: How to Safely Refactor Legacy CodeGene Gotimer
 
MongoDB Performance Tuning
MongoDB Performance TuningMongoDB Performance Tuning
MongoDB Performance TuningPuneet Behl
 
MongoDB Performance Tuning
MongoDB Performance TuningMongoDB Performance Tuning
MongoDB Performance TuningMongoDB
 
PostgreSQL Tutorial for Beginners | Edureka
PostgreSQL Tutorial for Beginners | EdurekaPostgreSQL Tutorial for Beginners | Edureka
PostgreSQL Tutorial for Beginners | EdurekaEdureka!
 
Clean Pragmatic Architecture - Avoiding a Monolith
Clean Pragmatic Architecture - Avoiding a MonolithClean Pragmatic Architecture - Avoiding a Monolith
Clean Pragmatic Architecture - Avoiding a MonolithVictor Rentea
 
Understand front end developer
Understand front end developerUnderstand front end developer
Understand front end developerHsuan Fu Lien
 
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 QueryMongoDB
 
APEX richtig installieren und konfigurieren
APEX richtig installieren und konfigurierenAPEX richtig installieren und konfigurieren
APEX richtig installieren und konfigurierenOliver Lemm
 
JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)
JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)
JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)Stephen Chin
 
MySQL Indexing - Best practices for MySQL 5.6
MySQL Indexing - Best practices for MySQL 5.6MySQL Indexing - Best practices for MySQL 5.6
MySQL Indexing - Best practices for MySQL 5.6MYXPLAIN
 
Row Pattern Matching in SQL:2016
Row Pattern Matching in SQL:2016Row Pattern Matching in SQL:2016
Row Pattern Matching in SQL:2016Markus Winand
 
The Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable DesignThe Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable DesignVictor Rentea
 
MySQL: Indexing for Better Performance
MySQL: Indexing for Better PerformanceMySQL: Indexing for Better Performance
MySQL: Indexing for Better Performancejkeriaki
 
Mysql Explain Explained
Mysql Explain ExplainedMysql Explain Explained
Mysql Explain ExplainedJeremy Coates
 
MySQL Index Cookbook
MySQL Index CookbookMySQL Index Cookbook
MySQL Index CookbookMYXPLAIN
 

Was ist angesagt? (20)

Parallel Query in AWS Aurora MySQL
Parallel Query in AWS Aurora MySQLParallel Query in AWS Aurora MySQL
Parallel Query in AWS Aurora MySQL
 
Get to Green: How to Safely Refactor Legacy Code
Get to Green: How to Safely Refactor Legacy CodeGet to Green: How to Safely Refactor Legacy Code
Get to Green: How to Safely Refactor Legacy Code
 
MongoDB Performance Tuning
MongoDB Performance TuningMongoDB Performance Tuning
MongoDB Performance Tuning
 
MongoDB Performance Tuning
MongoDB Performance TuningMongoDB Performance Tuning
MongoDB Performance Tuning
 
PostgreSQL Tutorial for Beginners | Edureka
PostgreSQL Tutorial for Beginners | EdurekaPostgreSQL Tutorial for Beginners | Edureka
PostgreSQL Tutorial for Beginners | Edureka
 
Clean Pragmatic Architecture - Avoiding a Monolith
Clean Pragmatic Architecture - Avoiding a MonolithClean Pragmatic Architecture - Avoiding a Monolith
Clean Pragmatic Architecture - Avoiding a Monolith
 
Understand front end developer
Understand front end developerUnderstand front end developer
Understand front end developer
 
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
 
APEX richtig installieren und konfigurieren
APEX richtig installieren und konfigurierenAPEX richtig installieren und konfigurieren
APEX richtig installieren und konfigurieren
 
Clean code
Clean codeClean code
Clean code
 
Refactoring
RefactoringRefactoring
Refactoring
 
JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)
JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)
JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)
 
MySQL Indexing - Best practices for MySQL 5.6
MySQL Indexing - Best practices for MySQL 5.6MySQL Indexing - Best practices for MySQL 5.6
MySQL Indexing - Best practices for MySQL 5.6
 
Row Pattern Matching in SQL:2016
Row Pattern Matching in SQL:2016Row Pattern Matching in SQL:2016
Row Pattern Matching in SQL:2016
 
Testing In Java
Testing In JavaTesting In Java
Testing In Java
 
Full Text Search In PostgreSQL
Full Text Search In PostgreSQLFull Text Search In PostgreSQL
Full Text Search In PostgreSQL
 
The Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable DesignThe Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable Design
 
MySQL: Indexing for Better Performance
MySQL: Indexing for Better PerformanceMySQL: Indexing for Better Performance
MySQL: Indexing for Better Performance
 
Mysql Explain Explained
Mysql Explain ExplainedMysql Explain Explained
Mysql Explain Explained
 
MySQL Index Cookbook
MySQL Index CookbookMySQL Index Cookbook
MySQL Index Cookbook
 

Ähnlich wie MongoDB Shell Tips & Tricks

Shell Tips and Tricks
Shell Tips and TricksShell Tips and Tricks
Shell Tips and TricksMongoDB
 
MongoDB at the Silicon Valley iPhone and iPad Developers' Meetup
MongoDB at the Silicon Valley iPhone and iPad Developers' MeetupMongoDB at the Silicon Valley iPhone and iPad Developers' Meetup
MongoDB at the Silicon Valley iPhone and iPad Developers' MeetupMongoDB
 
Shell Tips & Tricks
Shell Tips & TricksShell Tips & Tricks
Shell Tips & TricksMongoDB
 
Webinar: Was ist neu in MongoDB 2.4
Webinar: Was ist neu in MongoDB 2.4Webinar: Was ist neu in MongoDB 2.4
Webinar: Was ist neu in MongoDB 2.4MongoDB
 
MongoDB Auto-Sharding at Mongo Seattle
MongoDB Auto-Sharding at Mongo SeattleMongoDB Auto-Sharding at Mongo Seattle
MongoDB Auto-Sharding at Mongo SeattleMongoDB
 
Mongodb intro
Mongodb introMongodb intro
Mongodb introchristkv
 
MongoDB at ZPUGDC
MongoDB at ZPUGDCMongoDB at ZPUGDC
MongoDB at ZPUGDCMike Dirolf
 
Buildingsocialanalyticstoolwithmongodb
BuildingsocialanalyticstoolwithmongodbBuildingsocialanalyticstoolwithmongodb
BuildingsocialanalyticstoolwithmongodbMongoDB APAC
 
Modern, Scalable, Ambitious apps with Ember.js
Modern, Scalable, Ambitious apps with Ember.jsModern, Scalable, Ambitious apps with Ember.js
Modern, Scalable, Ambitious apps with Ember.jsMike North
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDBJustin Smestad
 
MongoDB at FrozenRails
MongoDB at FrozenRailsMongoDB at FrozenRails
MongoDB at FrozenRailsMike Dirolf
 
Exploring Clojurescript
Exploring ClojurescriptExploring Clojurescript
Exploring ClojurescriptLuke Donnet
 
Scaling with MongoDB
Scaling with MongoDBScaling with MongoDB
Scaling with MongoDBRick Copeland
 
AI與大數據數據處理 Spark實戰(20171216)
AI與大數據數據處理 Spark實戰(20171216)AI與大數據數據處理 Spark實戰(20171216)
AI與大數據數據處理 Spark實戰(20171216)Paul Chao
 
MongoDB at Scale
MongoDB at ScaleMongoDB at Scale
MongoDB at ScaleMongoDB
 
Mongo Berlin - Mastering the Shell
Mongo Berlin - Mastering the ShellMongo Berlin - Mastering the Shell
Mongo Berlin - Mastering the ShellMongoDB
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDBantoinegirbal
 
2011 Mongo FR - MongoDB introduction
2011 Mongo FR - MongoDB introduction2011 Mongo FR - MongoDB introduction
2011 Mongo FR - MongoDB introductionantoinegirbal
 

Ähnlich wie MongoDB Shell Tips & Tricks (20)

Shell Tips and Tricks
Shell Tips and TricksShell Tips and Tricks
Shell Tips and Tricks
 
MongoDB at the Silicon Valley iPhone and iPad Developers' Meetup
MongoDB at the Silicon Valley iPhone and iPad Developers' MeetupMongoDB at the Silicon Valley iPhone and iPad Developers' Meetup
MongoDB at the Silicon Valley iPhone and iPad Developers' Meetup
 
Shell Tips & Tricks
Shell Tips & TricksShell Tips & Tricks
Shell Tips & Tricks
 
MongoDB Webtech conference 2010
MongoDB Webtech conference 2010MongoDB Webtech conference 2010
MongoDB Webtech conference 2010
 
Webinar: Was ist neu in MongoDB 2.4
Webinar: Was ist neu in MongoDB 2.4Webinar: Was ist neu in MongoDB 2.4
Webinar: Was ist neu in MongoDB 2.4
 
MongoDB Auto-Sharding at Mongo Seattle
MongoDB Auto-Sharding at Mongo SeattleMongoDB Auto-Sharding at Mongo Seattle
MongoDB Auto-Sharding at Mongo Seattle
 
MongoDB 3.0
MongoDB 3.0 MongoDB 3.0
MongoDB 3.0
 
Mongodb intro
Mongodb introMongodb intro
Mongodb intro
 
MongoDB at ZPUGDC
MongoDB at ZPUGDCMongoDB at ZPUGDC
MongoDB at ZPUGDC
 
Buildingsocialanalyticstoolwithmongodb
BuildingsocialanalyticstoolwithmongodbBuildingsocialanalyticstoolwithmongodb
Buildingsocialanalyticstoolwithmongodb
 
Modern, Scalable, Ambitious apps with Ember.js
Modern, Scalable, Ambitious apps with Ember.jsModern, Scalable, Ambitious apps with Ember.js
Modern, Scalable, Ambitious apps with Ember.js
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
MongoDB at FrozenRails
MongoDB at FrozenRailsMongoDB at FrozenRails
MongoDB at FrozenRails
 
Exploring Clojurescript
Exploring ClojurescriptExploring Clojurescript
Exploring Clojurescript
 
Scaling with MongoDB
Scaling with MongoDBScaling with MongoDB
Scaling with MongoDB
 
AI與大數據數據處理 Spark實戰(20171216)
AI與大數據數據處理 Spark實戰(20171216)AI與大數據數據處理 Spark實戰(20171216)
AI與大數據數據處理 Spark實戰(20171216)
 
MongoDB at Scale
MongoDB at ScaleMongoDB at Scale
MongoDB at Scale
 
Mongo Berlin - Mastering the Shell
Mongo Berlin - Mastering the ShellMongo Berlin - Mastering the Shell
Mongo Berlin - Mastering the Shell
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
2011 Mongo FR - MongoDB introduction
2011 Mongo FR - MongoDB introduction2011 Mongo FR - MongoDB introduction
2011 Mongo FR - MongoDB introduction
 

Mehr von MongoDB

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 AtlasMongoDB
 
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
 
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
 
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 MongoDBMongoDB
 
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
 
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 DataMongoDB
 
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 StartMongoDB
 
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
 
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.2MongoDB
 
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
 
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
 
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 MindsetMongoDB
 
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 JumpstartMongoDB
 
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
 
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
 
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
 
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 DiveMongoDB
 
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 & GolangMongoDB
 
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
 
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...MongoDB
 

Mehr von 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...
 

MongoDB Shell Tips & Tricks

  • 1. #MongoDBDays MongoDB Shell Tips & Tricks Hannes Magnusson Driver Engineer, 10gen @bjori
  • 2. What is the Shell? Embedded • vars / functions / data structs + types Javascript • Spidermonkey / V8 Interpreter • ObjectId("...") Global Functions • new Date() and Objects • Object.bsonsize() MongoDB driver • db["collection"].find/count/update Exposed • short-hand for collections • Doesn't require quoted keys JSON-like stuff • Don’t copy and paste too much Shell Tips & Tricks, Hannes Magnusson
  • 3. MongoDB Shell: Advantages • Your goto tool • Debugging Queries / Syntax • Testing • Administration • Scripting Glue • You don’t do rs.stepDown() from your application Shell Tips & Tricks, Hannes Magnusson
  • 4. MongoDB Shell: Disadvantages • Numbers in JS are a pain – 32/64-bit int/long  NumberInt() / NumberLong() – Primitive numbers are all 64-bit FP doubles • Dates can be confusing – new Date( "1/1/1" ) – new ISODate( ... ) NOT: Date( "1/1/1" )  string Shell Tips & Tricks, Hannes Magnusson
  • 5. Emacs-like shell bindings ctrl A Move cursor to start of line ctrl E Move cursor to end of line meta B Move cursor left by one word meta F Move cursor right by one word ctrl L Clear screen and redisplay line ctrl R Reverse history search meta < Start of history meta > End of history Shell Tips & Tricks, Hannes Magnusson
  • 7. Emacs-like shell bindings ctrl A Move cursor to start of line ctrl E Move cursor to end of line meta B Move cursor left by one word meta F Move cursor right by one word ctrl L Clear screen and redisplay line ctrl R Reverse history search meta < Start of history meta > End of history Shell Tips & Tricks, Hannes Magnusson
  • 8. Easy to use • Tab completion on most objects • Built-in help on most objects (.help()) • show – profile # 5 most recent ops of 1ms or more – users # List all the users of the current db – dbs # List all the databases – logs # List all available logs • Most examples use the shell Shell Tips & Tricks, Hannes Magnusson
  • 9. Speed Considerations • Shell – JavaScript is slow – Always in "write-acknowledged" (safe mode) / GLE – Data Conversions • Server – Applies on the server as well – Careful with round-tripping numbers Shell Tips & Tricks, Hannes Magnusson
  • 10. Insert, Update, Remove for ( i = 0; i < 1000; i++ ) { db.test.insert( { x: i, ts: new Date() } ); } Shell Tips & Tricks, Hannes Magnusson
  • 11. Loading Scripts • Commandline – --eval switch – .js files • Within the shell – load() Shell Tips & Tricks, Hannes Magnusson
  • 12. Running Commands • db.runCommand( { ... } ) – Runs any arbitrary command against the current DB • db.adminCommand( { ... } ) – Run commands against the admin database Shell Tips & Tricks, Hannes Magnusson
  • 13. db.adminCommand Definition function (obj) { if (this._name == "admin") { return this.runCommand(obj); } return this.getSiblingDB("admin") .runCommand(obj); } Shell Tips & Tricks, Hannes Magnusson
  • 14. Profiling • setProfilingLevel( lvl, <ms> ) – 0: none – 1: time-based – 2: all • getProfilingLevel() • Reading from the profile collection – db.system.profile.find() Shell Tips & Tricks, Hannes Magnusson
  • 15. Cool Functions • printjson()  tojson • forEach on arrays, queries, and cursors Shell Tips & Tricks, Hannes Magnusson
  • 16. You didn’t hear it from me db.system.js.save({ _id:"echoFunction", value : function(x) { return x; } }) db.loadServerScripts(); echoFunction(3); Shell Tips & Tricks, Hannes Magnusson
  • 18. forEach example [{x:1},{y:1}].forEach(function(x) { printjson(x) }) { "x" : 1 } { "y" : 1 } Shell Tips & Tricks, Hannes Magnusson
  • 19. Cool Functions • printjson  tojson • forEach on arrays, queries, and cursors • Object.bsonsize • load(file) • run(file) Shell Tips & Tricks, Hannes Magnusson
  • 20. Print all Indexes db.getCollectionNames(). forEach( function(x) { print( "Collection: " + x ); printjson( db[x].getIndexes() ); }) Shell Tips & Tricks, Hannes Magnusson
  • 21. Getting the Biggest Doc 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; } }); Shell Tips & Tricks, Hannes Magnusson
  • 22. Administration functions • Sharding – sh.status() – sh.enableSharding(dbname) • Replicaset – rs.status() – cfg = rs.config(); rs.reconfig(cfg); – db.isMaster() • Status – Object.bsonsize(document) – db.collectionName.stats() Shell Tips & Tricks, Hannes Magnusson
  • 24. .mongorc.js • Automagically loaded on startup – Unless you specify --norc • Script your command prompt – prompt=function() { return "Hello World"; } • Colorize output • Move complex aggregate() queries into functions • Can be a directory Shell Tips & Tricks, Hannes Magnusson
  • 25. Want to know more? The shell is self documented, in JavaScript o/ …Except the native helper • help – dbs # Shows all commands you can run on a database – connect # Connect to other nodes • Call a function, without the brackets – Will show you the actual code behind it • try.mongodb.org ! Shell Tips & Tricks, Hannes Magnusson

Hinweis der Redaktion

  1. http://try.mongodb.org/– it is almost a full clone of the shellThe shell is your buddy, your goto tool for quick hacking/tasksIt is important to know and bridges everyone using MongoDB as it doesn’t include any of the language specific cruft or dependencies– just raw MongoDB :D !
  2. Doesn’t matter which language you use, everyone else knows the shellAll examples during this conference are based on the shell
  3. ----- Meeting Notes (1/16/13 17:30) -----anecdote
  4. Unfortunately, we hire a lot of Brown students who apparently learn emacs :(No vi bindings… YET!
  5. Unfortunately, we hire a lot of Brown students who apparently learn emacs :(No vi bindings… YET!
  6. Believe it or not, show tables works too :PIf you care what is behind it, serverBuildInfo.interpreterVersionIt’s the common ground between the languages
  7. Show Demo #1
  8. Show Demo #2
  9. See implementation by omitting parens()
  10. do demo #3
  11. do demo #4