Databases Reference
In-Depth Information
For example, suppose we are using
“Tip #46: Manage all of your servers and databases
from one shell” on page 46
to connect to every member of a replica set and we want to
add a
getOplogLength
function.
If we think of this before we get started, we could add it to the database class (
DB
):
DB.prototype.getOplogLength = function() {
var local = this.getSisterDB("local");
var first = local.oplog.rs.find().sort({$natural : 1}).limit(1).next();
var last = local.oplog.rs.find().sort({$natural : -1}).limit(1).next();
print("total time: " + (last.ts.t - first.ts.t) + " secs");
};
Then, when we connect to
rsA
,
rsB
, and
rsC
databases, each will have a
getOplogSize
method.
If we've already started using
rsA
,
rsB
, and
rsC
, then they won't pick up that you added
a new method to the class that they came from (classes in JavaScript are sort of like
templates for class instances: the instance has no dependency on the class once it's
initialized). If the connections have already been initialized, you can add this method
to each instance:
// store the function in a variable to save typing
var f = function() { ... }
rsA.getOplogSize = f;
rsB.getOplogSize = f;
rsC.getOplogSize = f;
You could also just alter it slightly to be a global function:
getOplogLength = function(db) {
var local = db.getSisterDB("local");
...
};
You can, of course, also do this for an object's fields (as well as its methods).
Loading JavaScript from files
You can add JavaScript libraries to your shell at any time using the
load()
function.
load()
takes a JavaScript file and executes it in the context of the shell (so it will know
about all of the global variables in the shell). You can also add variables to the shell's
global scope by defining them in loaded files. You can also print output from these files
to the shell using the
print
function:
// hello.js
print("Hello, world!")
Then, in the shell:
> load("hello.js")
Hello, world!