Upload
scott-hernandez
View
12.333
Download
1
Embed Size (px)
Citation preview
MASTERING THE SHELL
Raw MongoDB (as you like it)
What is the shell?
•vars•funct
ions•data
structs + types
Embedded Javascript Interpreter
•ObjectId("...")
•new Date()
•Object.bsonsize()
Global Functions and Objects
•db["collection"].find/count/update
•short-hand for collections
MongoDB driver Exposed
•Doesn't require quoted keys
•Don’t copy and paste too much
JSON-like stuff
What is it good for?
Debugging Testing Administration Scripting Glue Not building apps, probably
The Bad: JS Types
Numbers Suck (but getting better) 32/64bit signed (int/long) –
1.5.4>NumberLong(“”) Displayed funny Everything is a 64bit fp (double)
Dates are a challenge new Date(“1/1/1”) Not Date(“1/1/1”) -> string
The Bad: JS is Slow
Shell Safe/GLE Loops and updates Data conversions
Server It pretty much applies here too Be careful with numbers as well
Insert, Save, Update, Remove Demo now
for(i = 0; i <1000; i++) { db.test.insert({x:i, ts: new Date()}) }
Command Line
--eval it/cursor Printing values
Pass in a script
Loading Scripts
Command line load() – also runs
Run Commands
db.runCommand({…})
db.runCommand(“getLastError”)
Useful Commands
getCmdLineOpts ping isMaster reIndex sharding replication
Profiling
setProfilingLevel(lvl, <ms>) 0: none 1: time-based 2: all
Reading from profile collection>db.system.profile.find()
Help
> help> help admin> help misc> db.help()> db.coll.help()
Expose Functions
Leave off the () to see the function:
> db.getSisterDBfunction (name) { return this.getMongo().getDB(name);
Cool functions
printjson -> tojson forEach on array/query/cursor> [{x:1},{y:1}].forEach(function(x){printjson(x)})
{ "x" : 1 }
{ "y" : 1 }
Object.bsonsizeObject.bsonsize(c.findOne({name:”scott”}))
load(file) run(file)
Print all Indexes
db.getCollectionNames().forEach(function(x){
print(“Collection: “ + x);printjson(db[x].getIndexes());
})
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; }
});
Cursors: it
“it” global var find automatically sets it
Aliases
Show collections/tables
DBRef
Has fetch() Easy to create