Skip to content

Instantly share code, notes, and snippets.

@subfuzion
Created February 26, 2014 19:14
Show Gist options
  • Save subfuzion/9236373 to your computer and use it in GitHub Desktop.
Save subfuzion/9236373 to your computer and use it in GitHub Desktop.
mongo shell helpers

You can load helper functions from a JavaScript file to make working with data in the mongo shell easier.

I typically like to create a queries.js file that contains a number of helper functions. You load a file in the shell like this:

> load('queries.js')

Since I keep editing the file and adding more helpers as I'm working, I usually add a helper function to the file that reloads itself to save a few keystrokes. Yup, I'm that lazy.

function update() {
  load('queries.js')
}

Examples of helper functions are things that help me when I'm looking at logs generated from an app.

A common use case for me is when I see a clientid and want to get the user details. Or maybe I want to test submitting a request using curl for a particular user and I need the user's credentials (in this example, an api key) given the username. You get the idea.

function clientid(id) {
  return db.users.findOne({ _id: ObjectId(id)});
}

function credentials(username) {
  var result = db.users.findOne({username: username}, { apikey:1, token:1 });
  
  if (result) {
    result = {
      username: result.username,
      clientid: result._id.str,
      apikey: result.apikey
    };
  }
  
  return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment