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