Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Advanced Shell Tips and Tricks

Sponsored · Your Podcast. Everywhere. Effortlessly. Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
Avatar for mongodb mongodb
April 20, 2012
320

Advanced Shell Tips and Tricks

MongoDB Stockholm 2012 - Advanced Shell Tips and Tricks - Spencer Brody, Engineer, 10gen

Avatar for mongodb

mongodb

April 20, 2012
Tweet

Transcript

  1. 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 much JSON-like stuff
  2. What is it good for? ¨  Interactive development/prototyping ¨  Debugging

    ¨  Test scripting (ex. MongoDB’s own regression tests) ¨  Administrative operations, lightweight scripting ¨  Learning (and teaching) MongoDB ¨  Not building apps, probably
  3. Interactive mode ¨  Demo now J ¨  for(i = 0;

    i <1000; i++) { db.test.insert({x:i, ts: new Date()}) }
  4. 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
  5. 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
  6. Cursors ¨  Cursors printed by iterating and printing 20 values

    ¨  find automatically sets “it” global var ¨  Cursors as first-class objects
  7. Help > help > help admin > help misc >

    db.help() > db.coll.help()
  8. Expose Functions ¨  Leave off the () to see the

    function: > db.getSiblingDB function (name) { return this.getMongo().getDB(name);
  9. Cool functions ¨  printjson -> tojson ¨  forEach on array/query/cursor

    > [{x:1},{y:1}].forEach(function(x){printjson(x)}) { "x" : 1 } { "y" : 1 } ¨  Object.bsonsize Object.bsonsize(c.findOne({name:”scott”})) ¨  load(file) ¨  run(file)
  10. 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; } });
  11. .mongorc.js ¨  File loaded at startup ¨  Can be used

    to setup functions you always want defined ¨  Can set custom prompts