SlideShare a Scribd company logo
#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
Ad

More Related Content

What's hot (20)

[OpenStack 하반기 스터디] Interoperability with ML2: LinuxBridge, OVS and SDN
[OpenStack 하반기 스터디] Interoperability with ML2: LinuxBridge, OVS and SDN[OpenStack 하반기 스터디] Interoperability with ML2: LinuxBridge, OVS and SDN
[OpenStack 하반기 스터디] Interoperability with ML2: LinuxBridge, OVS and SDN
OpenStack Korea Community
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
Purbarun Chakrabarti
 
Spring boot jpa
Spring boot jpaSpring boot jpa
Spring boot jpa
Hamid Ghorbani
 
Docker Swarm for Beginner
Docker Swarm for BeginnerDocker Swarm for Beginner
Docker Swarm for Beginner
Shahzad Masud
 
C# - Part 1
C# - Part 1C# - Part 1
C# - Part 1
Md. Mahedee Hasan
 
ORM: Object-relational mapping
ORM: Object-relational mappingORM: Object-relational mapping
ORM: Object-relational mapping
Abhilash M A
 
Tomcat
TomcatTomcat
Tomcat
Venkat Pinagadi
 
Introduction to Apache Camel
Introduction to Apache CamelIntroduction to Apache Camel
Introduction to Apache Camel
Claus Ibsen
 
Real Life Clean Architecture
Real Life Clean ArchitectureReal Life Clean Architecture
Real Life Clean Architecture
Mattia Battiston
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
Shaul Rosenzwieg
 
A python web service
A python web serviceA python web service
A python web service
Temian Vlad
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
Sony India Software Center
 
MYSQL - PHP Database Connectivity
MYSQL - PHP Database ConnectivityMYSQL - PHP Database Connectivity
MYSQL - PHP Database Connectivity
V.V.Vanniaperumal College for Women
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
kamal kotecha
 
Introduction to Spring Cloud
Introduction to Spring Cloud           Introduction to Spring Cloud
Introduction to Spring Cloud
VMware Tanzu
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
Sehwan Noh
 
JDBC
JDBCJDBC
JDBC
People Strategists
 
Containerization & Docker - Under the Hood
Containerization & Docker - Under the HoodContainerization & Docker - Under the Hood
Containerization & Docker - Under the Hood
Imesha Sudasingha
 
An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
Aniruddh Bhilvare
 
Indexing with MongoDB
Indexing with MongoDBIndexing with MongoDB
Indexing with MongoDB
MongoDB
 
[OpenStack 하반기 스터디] Interoperability with ML2: LinuxBridge, OVS and SDN
[OpenStack 하반기 스터디] Interoperability with ML2: LinuxBridge, OVS and SDN[OpenStack 하반기 스터디] Interoperability with ML2: LinuxBridge, OVS and SDN
[OpenStack 하반기 스터디] Interoperability with ML2: LinuxBridge, OVS and SDN
OpenStack Korea Community
 
Docker Swarm for Beginner
Docker Swarm for BeginnerDocker Swarm for Beginner
Docker Swarm for Beginner
Shahzad Masud
 
ORM: Object-relational mapping
ORM: Object-relational mappingORM: Object-relational mapping
ORM: Object-relational mapping
Abhilash M A
 
Introduction to Apache Camel
Introduction to Apache CamelIntroduction to Apache Camel
Introduction to Apache Camel
Claus Ibsen
 
Real Life Clean Architecture
Real Life Clean ArchitectureReal Life Clean Architecture
Real Life Clean Architecture
Mattia Battiston
 
A python web service
A python web serviceA python web service
A python web service
Temian Vlad
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
kamal kotecha
 
Introduction to Spring Cloud
Introduction to Spring Cloud           Introduction to Spring Cloud
Introduction to Spring Cloud
VMware Tanzu
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
Sehwan Noh
 
Containerization & Docker - Under the Hood
Containerization & Docker - Under the HoodContainerization & Docker - Under the Hood
Containerization & Docker - Under the Hood
Imesha Sudasingha
 
Indexing with MongoDB
Indexing with MongoDBIndexing with MongoDB
Indexing with MongoDB
MongoDB
 

Similar to MongoDB Shell Tips & Tricks (20)

Shell Tips and Tricks
Shell Tips and TricksShell Tips and Tricks
Shell Tips and Tricks
MongoDB
 
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
MongoDB
 
Shell Tips & Tricks
Shell Tips & TricksShell Tips & Tricks
Shell Tips & Tricks
MongoDB
 
MongoDB Webtech conference 2010
MongoDB Webtech conference 2010MongoDB Webtech conference 2010
MongoDB Webtech conference 2010
Massimiliano Dessì
 
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
 
MongoDB Auto-Sharding at Mongo Seattle
MongoDB Auto-Sharding at Mongo SeattleMongoDB Auto-Sharding at Mongo Seattle
MongoDB Auto-Sharding at Mongo Seattle
MongoDB
 
MongoDB 3.0
MongoDB 3.0 MongoDB 3.0
MongoDB 3.0
Victoria Malaya
 
Mongodb intro
Mongodb introMongodb intro
Mongodb intro
christkv
 
MongoDB at ZPUGDC
MongoDB at ZPUGDCMongoDB at ZPUGDC
MongoDB at ZPUGDC
Mike Dirolf
 
Buildingsocialanalyticstoolwithmongodb
BuildingsocialanalyticstoolwithmongodbBuildingsocialanalyticstoolwithmongodb
Buildingsocialanalyticstoolwithmongodb
MongoDB 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.js
Mike North
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
Justin Smestad
 
MongoDB at FrozenRails
MongoDB at FrozenRailsMongoDB at FrozenRails
MongoDB at FrozenRails
Mike Dirolf
 
Exploring Clojurescript
Exploring ClojurescriptExploring Clojurescript
Exploring Clojurescript
Luke Donnet
 
Scaling with MongoDB
Scaling with MongoDBScaling with MongoDB
Scaling with MongoDB
Rick 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 Scale
MongoDB
 
Mongo Berlin - Mastering the Shell
Mongo Berlin - Mastering the ShellMongo Berlin - Mastering the Shell
Mongo Berlin - Mastering the Shell
MongoDB
 
Mastering the MongoDB Shell
Mastering the MongoDB ShellMastering the MongoDB Shell
Mastering the MongoDB Shell
MongoDB
 
2011 Mongo FR - MongoDB introduction
2011 Mongo FR - MongoDB introduction2011 Mongo FR - MongoDB introduction
2011 Mongo FR - MongoDB introduction
antoinegirbal
 
Shell Tips and Tricks
Shell Tips and TricksShell Tips and Tricks
Shell Tips and Tricks
MongoDB
 
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
MongoDB
 
Shell Tips & Tricks
Shell Tips & TricksShell Tips & Tricks
Shell Tips & Tricks
MongoDB
 
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
 
MongoDB Auto-Sharding at Mongo Seattle
MongoDB Auto-Sharding at Mongo SeattleMongoDB Auto-Sharding at Mongo Seattle
MongoDB Auto-Sharding at Mongo Seattle
MongoDB
 
Mongodb intro
Mongodb introMongodb intro
Mongodb intro
christkv
 
MongoDB at ZPUGDC
MongoDB at ZPUGDCMongoDB at ZPUGDC
MongoDB at ZPUGDC
Mike Dirolf
 
Buildingsocialanalyticstoolwithmongodb
BuildingsocialanalyticstoolwithmongodbBuildingsocialanalyticstoolwithmongodb
Buildingsocialanalyticstoolwithmongodb
MongoDB 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.js
Mike North
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
Justin Smestad
 
MongoDB at FrozenRails
MongoDB at FrozenRailsMongoDB at FrozenRails
MongoDB at FrozenRails
Mike Dirolf
 
Exploring Clojurescript
Exploring ClojurescriptExploring Clojurescript
Exploring Clojurescript
Luke Donnet
 
Scaling with MongoDB
Scaling with MongoDBScaling with MongoDB
Scaling with MongoDB
Rick 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 Scale
MongoDB
 
Mongo Berlin - Mastering the Shell
Mongo Berlin - Mastering the ShellMongo Berlin - Mastering the Shell
Mongo Berlin - Mastering the Shell
MongoDB
 
Mastering the MongoDB Shell
Mastering the MongoDB ShellMastering the MongoDB Shell
Mastering the MongoDB Shell
MongoDB
 
2011 Mongo FR - MongoDB introduction
2011 Mongo FR - MongoDB introduction2011 Mongo FR - MongoDB introduction
2011 Mongo FR - MongoDB introduction
antoinegirbal
 
Ad

More from 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
 
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 MongoDB
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
 
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
 
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
 
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.2
MongoDB
 
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 Mindset
MongoDB
 
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
 
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 Dive
MongoDB
 
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
 
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
 
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
 
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 MongoDB
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
 
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
 
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
 
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.2
MongoDB
 
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 Mindset
MongoDB
 
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
 
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 Dive
MongoDB
 
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
 
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
 
Ad

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

Editor's Notes

  • #2: 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 !
  • #4: Doesn’t matter which language you use, everyone else knows the shellAll examples during this conference are based on the shell
  • #5: ----- Meeting Notes (1/16/13 17:30) -----anecdote
  • #6: Unfortunately, we hire a lot of Brown students who apparently learn emacs :(No vi bindings… YET!
  • #8: Unfortunately, we hire a lot of Brown students who apparently learn emacs :(No vi bindings… YET!
  • #9: Believe it or not, show tables works too :PIf you care what is behind it, serverBuildInfo.interpreterVersionIt’s the common ground between the languages
  • #11: Show Demo #1
  • #12: Show Demo #2
  • #13: See implementation by omitting parens()
  • #21: do demo #3
  • #22: do demo #4