16

Click here to load reader

Shell Tips & Tricks

  • Upload
    mongodb

  • View
    142

  • Download
    1

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: Shell Tips & Tricks

Perl Engineer & Evangelist, 10gen

Mike Friedman

#MongoDBDays

MongoDB Shell Tips & Tricks

Page 2: Shell Tips & Tricks

What is the Shell?• vars• functions• 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 muchJSON-like stuff

Page 3: Shell Tips & Tricks

MongoDB Shell: Advantages• Debugging Queries / Syntax

• Testing

• Administration

• Scripting Glue

Page 4: Shell Tips & Tricks

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

Page 5: Shell Tips & Tricks

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

Page 6: Shell Tips & Tricks

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

Insert, Update, Remove

Page 7: Shell Tips & Tricks

Loading Scripts

• Commandline– --eval switch– .js files

• Within the shell– load()

Page 8: Shell Tips & Tricks

Running Commands

• db.runCommand( { ... } )– Runs any arbitrary command against the current

DB

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

Page 9: Shell Tips & Tricks

function (obj) { if (this._name == "admin") { return this.runCommand(obj); } return this.getSiblingDB("admin") .runCommand(obj);}

db.adminCommand Definition

Page 10: Shell Tips & Tricks

Profiling

• setProfilingLevel( lvl, <ms> )– 0: none– 1: time-based– 2: all

• getProfilingLevel()

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

Page 11: Shell Tips & Tricks

Cool Functions

• printjson tojson

• forEach on arrays, queries, and cursors

Page 12: Shell Tips & Tricks

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

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

forEach example

Page 13: Shell Tips & Tricks

Cool Functions

• printjson tojson

• forEach on arrays, queries, and cursors

• Object.bsonsize

• load(file)

• run(file)

Page 14: Shell Tips & Tricks

db.getCollectionNames().forEach( function(x) {

print( "Collection: " + x );printjson( db[x].getIndexes() );

})

Print all Indexes

Page 15: Shell Tips & Tricks

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; }});

Getting the Biggest Doc

Page 16: Shell Tips & Tricks

Perl Engineer & Evangelist, 10gen

Mike Friedman

#MongoDBDays

Thank You