summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMike Grundy <michael.grundy@10gen.com>2016-02-04 11:34:12 -0500
committerMike Grundy <michael.grundy@10gen.com>2016-02-05 15:15:00 -0500
commitc3996780b76316793758b43fa1fca5b9d0857b6c (patch)
tree48745d6c239724228f868593b36bddc981771542
parent6bf0dcee8a4027d98ef307b267121352fed070c4 (diff)
downloadmongo-c3996780b76316793758b43fa1fca5b9d0857b6c.tar.gz
SERVER-22340 Fix JS lint errors in src/mongo/ with ESLint --fix
-rw-r--r--src/mongo/scripting/mozjs/mongohelpers.js2
-rw-r--r--src/mongo/shell/assert.js74
-rw-r--r--src/mongo/shell/bulk_api.js132
-rw-r--r--src/mongo/shell/collection.js324
-rw-r--r--src/mongo/shell/crud_api.js36
-rw-r--r--src/mongo/shell/db.js184
-rw-r--r--src/mongo/shell/explain_query.js16
-rw-r--r--src/mongo/shell/explainable.js30
-rw-r--r--src/mongo/shell/mongo.js48
-rw-r--r--src/mongo/shell/mr.js12
-rw-r--r--src/mongo/shell/query.js224
-rwxr-xr-xsrc/mongo/shell/servers.js308
-rw-r--r--src/mongo/shell/servers_misc.js50
-rw-r--r--src/mongo/shell/types.js154
-rw-r--r--src/mongo/shell/utils.js168
-rw-r--r--src/mongo/shell/utils_sh.js310
16 files changed, 1036 insertions, 1036 deletions
diff --git a/src/mongo/scripting/mozjs/mongohelpers.js b/src/mongo/scripting/mozjs/mongohelpers.js
index 9756b3de3fe..2396d74efc6 100644
--- a/src/mongo/scripting/mozjs/mongohelpers.js
+++ b/src/mongo/scripting/mozjs/mongohelpers.js
@@ -93,7 +93,7 @@ exportToMongoHelpers = {
return 'function() { ' + fnSrc + ' }';
}
}
-}
+};
// WARNING: Anything outside the exportToMongoHelpers dictionary will be available in the
// global scope and visible to users!
diff --git a/src/mongo/shell/assert.js b/src/mongo/shell/assert.js
index e5ff934e1d8..b3b7947cf66 100644
--- a/src/mongo/shell/assert.js
+++ b/src/mongo/shell/assert.js
@@ -16,7 +16,7 @@ doassert = function(msg, obj) {
}
print(ex.stack);
throw ex;
-}
+};
assert = function(b, msg){
if (arguments.length > 2) {
@@ -29,11 +29,11 @@ assert = function(b, msg){
if (b)
return;
doassert(msg == undefined ? "assert failed" : "assert failed : " + msg);
-}
+};
assert.automsg = function(b) {
assert(eval(b), b);
-}
+};
assert._debug = false;
@@ -47,7 +47,7 @@ assert.eq = function(a, b, msg){
return;
doassert("[" + tojson(a) + "] != [" + tojson(b) + "] are not equal : " + msg);
-}
+};
// Sort doc/obj fields and return new sorted obj
sortDoc = function(doc) {
@@ -62,7 +62,7 @@ sortDoc = function(doc) {
}
return newArr;
- }
+ };
// not a container we can sort
if (!(doc instanceof Object))
@@ -96,7 +96,7 @@ sortDoc = function(doc) {
}
return newDoc;
-}
+};
assert.docEq = function(a, b, msg) {
if (assert._debug && msg) print("in assert for: " + msg);
@@ -111,11 +111,11 @@ assert.docEq = function(a, b, msg) {
return;
doassert("[" + tojson(aSorted) + "] != [" + tojson(bSorted) + "] are not equal : " + msg);
-}
+};
assert.eq.automsg = function(a, b) {
assert.eq(eval(a), eval(b), "[" + a + "] != [" + b + "]");
-}
+};
assert.neq = function(a, b, msg){
if (assert._debug && msg) print("in assert for: " + msg);
@@ -123,27 +123,27 @@ assert.neq = function(a, b, msg){
return;
doassert("[" + a + "] != [" + b + "] are equal : " + msg);
-}
+};
assert.contains = function(o, arr, msg){
- var wasIn = false
+ var wasIn = false;
if(! arr.length){
for(var i in arr){
- wasIn = arr[i] == o || ((arr[i] != null && o != null) && friendlyEqual(arr[i], o))
+ wasIn = arr[i] == o || ((arr[i] != null && o != null) && friendlyEqual(arr[i], o));
return;
- if(wasIn) break
+ if(wasIn) break;
}
}
else {
for(var i = 0; i < arr.length; i++){
- wasIn = arr[i] == o || ((arr[i] != null && o != null) && friendlyEqual(arr[i], o))
- if(wasIn) break
+ wasIn = arr[i] == o || ((arr[i] != null && o != null) && friendlyEqual(arr[i], o));
+ if(wasIn) break;
}
}
- if(! wasIn) doassert(tojson(o) + " was not in " + tojson(arr) + " : " + msg)
-}
+ if(! wasIn) doassert(tojson(o) + " was not in " + tojson(arr) + " : " + msg);
+};
assert.soon = function(f, msg, timeout /*ms*/, interval) {
if (assert._debug && msg) print("in assert for: " + msg);
@@ -177,7 +177,7 @@ assert.soon = function(f, msg, timeout /*ms*/, interval) {
}
sleep(interval);
}
-}
+};
assert.time = function(f, msg, timeout /*ms*/) {
if (assert._debug && msg) print("in assert for: " + msg);
@@ -195,7 +195,7 @@ assert.time = function(f, msg, timeout /*ms*/) {
if (diff > timeout)
doassert("assert.time failed timeout " + timeout + "ms took " + diff + "ms : " + f + ", msg:" + msg);
return res;
-}
+};
assert.throws = function(func, params, msg) {
if (assert._debug && msg) print("in assert for: " + msg);
@@ -240,7 +240,7 @@ assert.commandWorked = function(res, msg){
if (res.ok == 1)
return res;
doassert("command failed: " + tojson(res) + " : " + msg, res);
-}
+};
assert.commandFailed = function(res, msg){
if (assert._debug && msg) print("in assert for: " + msg);
@@ -248,7 +248,7 @@ assert.commandFailed = function(res, msg){
if (res.ok == 0)
return res;
doassert("command worked when it should have failed: " + tojson(res) + " : " + msg);
-}
+};
assert.commandFailedWithCode = function(res, code, msg){
if (assert._debug && msg) print("in assert for: " + msg);
@@ -258,7 +258,7 @@ assert.commandFailedWithCode = function(res, code, msg){
assert.eq(res.code, code, "Expected failure code did not match actual in command result: " +
tojson(res) + " : " + msg);
return res;
-}
+};
assert.isnull = function(what, msg){
if (assert._debug && msg) print("in assert for: " + msg);
@@ -266,7 +266,7 @@ assert.isnull = function(what, msg){
if (what == null)
return;
doassert("supposed to be null (" + (msg || "") + ") was: " + tojson(what));
-}
+};
assert.lt = function(a, b, msg){
if (assert._debug && msg) print("in assert for: " + msg);
@@ -274,7 +274,7 @@ assert.lt = function(a, b, msg){
if (a < b)
return;
doassert(a + " is not less than " + b + " : " + msg);
-}
+};
assert.gt = function(a, b, msg){
if (assert._debug && msg) print("in assert for: " + msg);
@@ -282,7 +282,7 @@ assert.gt = function(a, b, msg){
if (a > b)
return;
doassert(a + " is not greater than " + b + " : " + msg);
-}
+};
assert.lte = function(a, b, msg){
if (assert._debug && msg) print("in assert for: " + msg);
@@ -290,7 +290,7 @@ assert.lte = function(a, b, msg){
if (a <= b)
return;
doassert(a + " is not less than or eq " + b + " : " + msg);
-}
+};
assert.gte = function(a, b, msg){
if (assert._debug && msg) print("in assert for: " + msg);
@@ -298,7 +298,7 @@ assert.gte = function(a, b, msg){
if (a >= b)
return;
doassert(a + " is not greater than or eq " + b + " : " + msg);
-}
+};
assert.between = function(a, b, c, msg, inclusive){
if (assert._debug && msg) print("in assert for: " + msg);
@@ -307,10 +307,10 @@ assert.between = function(a, b, c, msg, inclusive){
a <= b && b <= c) return;
else if(a < b && b < c) return;
doassert(b + " is not between " + a + " and " + c + " : " + msg);
-}
+};
-assert.betweenIn = function(a, b, c, msg){ assert.between(a, b, c, msg, true) }
-assert.betweenEx = function(a, b, c, msg){ assert.between(a, b, c, msg, false) }
+assert.betweenIn = function(a, b, c, msg){ assert.between(a, b, c, msg, true); };
+assert.betweenEx = function(a, b, c, msg){ assert.between(a, b, c, msg, false); };
assert.close = function(a, b, msg, places){
if (places === undefined) {
@@ -391,7 +391,7 @@ assert.writeOK = function(res, msg) {
}
return res;
-}
+};
assert.writeError = function(res, msg) {
@@ -426,14 +426,14 @@ assert.writeError = function(res, msg) {
}
return res;
-}
+};
assert.gleOK = function(res, msg) {
var errMsg = null;
if (!res) {
- errMsg = "missing first argument, no response to check"
+ errMsg = "missing first argument, no response to check";
}
else if (!res.ok) {
errMsg = "getLastError failed: " + tojson(res);
@@ -450,7 +450,7 @@ assert.gleOK = function(res, msg) {
}
return res;
-}
+};
assert.gleSuccess = function(dbOrGLEDoc, msg) {
var gle = dbOrGLEDoc instanceof DB ? dbOrGLEDoc.getLastErrorObj() : dbOrGLEDoc;
@@ -460,7 +460,7 @@ assert.gleSuccess = function(dbOrGLEDoc, msg) {
doassert("getLastError not null:" + tojson(gle) + " :" + msg, gle);
}
return gle;
-}
+};
assert.gleError = function(dbOrGLEDoc, msg) {
var gle = dbOrGLEDoc instanceof DB ? dbOrGLEDoc.getLastErrorObj() : dbOrGLEDoc;
@@ -469,7 +469,7 @@ assert.gleError = function(dbOrGLEDoc, msg) {
msg = msg(gle);
doassert("getLastError is null: " + tojson(gle) + " :" + msg);
}
-}
+};
assert.gleErrorCode = function(dbOrGLEDoc, code, msg) {
var gle = dbOrGLEDoc instanceof DB ? dbOrGLEDoc.getLastErrorObj() : dbOrGLEDoc;
@@ -479,7 +479,7 @@ assert.gleErrorCode = function(dbOrGLEDoc, code, msg) {
doassert("getLastError is null or has code other than \"" + code + "\": "
+ tojson(gle) + " :" + msg);
}
-}
+};
assert.gleErrorRegex = function(dbOrGLEDoc, regex, msg) {
var gle = dbOrGLEDoc instanceof DB ? dbOrGLEDoc.getLastErrorObj() : dbOrGLEDoc;
@@ -489,4 +489,4 @@ assert.gleErrorRegex = function(dbOrGLEDoc, regex, msg) {
doassert("getLastError is null or doesn't match regex (" + regex + "): "
+ tojson(gle) + " :" + msg);
}
-}
+};
diff --git a/src/mongo/shell/bulk_api.js b/src/mongo/shell/bulk_api.js
index c20c84be874..96e078ec49a 100644
--- a/src/mongo/shell/bulk_api.js
+++ b/src/mongo/shell/bulk_api.js
@@ -7,7 +7,7 @@ var _bulk_api_module = (function() {
var NONE = 0;
var INSERT = 1;
var UPDATE = 2;
- var REMOVE = 3
+ var REMOVE = 3;
// Error codes
var UNKNOWN_ERROR = 8;
@@ -28,7 +28,7 @@ var _bulk_api_module = (function() {
return value;
}
});
- }
+ };
/**
* Shell representation of WriteConcern, possibly includes:
@@ -49,7 +49,7 @@ var _bulk_api_module = (function() {
if (arguments.length == 1)
opts = Object.merge(wValue);
else
- throw Error("If the first arg is an Object then no additional args are allowed!")
+ throw Error("If the first arg is an Object then no additional args are allowed!");
} else {
if (typeof wValue != 'undefined')
opts.w = wValue;
@@ -61,7 +61,7 @@ var _bulk_api_module = (function() {
// Do basic validation.
if (typeof opts.w != 'undefined' && typeof opts.w != 'number' && typeof opts.w != 'string')
- throw Error("w value must be a number or string but was found to be a " + typeof opts.w)
+ throw Error("w value must be a number or string but was found to be a " + typeof opts.w);
if (typeof opts.w == 'number' && NumberInt( opts.w ).toNumber() < 0)
throw Error("Numeric w value must be equal to or larger than 0, not " + opts.w);
@@ -159,7 +159,7 @@ var _bulk_api_module = (function() {
* @return {string}
*/
this.tojson = function(indent, nolint) {
- var result = {}
+ var result = {};
if(singleBatchType == INSERT) {
result.nInserted = this.nInserted;
@@ -198,7 +198,7 @@ var _bulk_api_module = (function() {
this.toString = function() {
// Suppress all output for the write concern w:0, since the client doesn't care.
if(writeConcern && writeConcern.w == 0) {
- return "WriteResult(" + tojson({}) + ")";;
+ return "WriteResult(" + tojson({}) + ")";
}
return "WriteResult(" + this.tojson() + ")";
};
@@ -228,40 +228,40 @@ var _bulk_api_module = (function() {
// Define access methods
this.getUpsertedIds = function() {
return bulkResult.upserted;
- }
+ };
this.getUpsertedIdAt = function(index) {
return bulkResult.upserted[index];
- }
+ };
this.getRawResponse = function() {
return bulkResult;
- }
+ };
this.hasWriteErrors = function() {
return bulkResult.writeErrors.length > 0;
- }
+ };
this.getWriteErrorCount = function() {
return bulkResult.writeErrors.length;
- }
+ };
this.getWriteErrorAt = function(index) {
if(index < bulkResult.writeErrors.length) {
return bulkResult.writeErrors[index];
}
return null;
- }
+ };
//
// Get all errors
this.getWriteErrors = function() {
return bulkResult.writeErrors;
- }
+ };
this.hasWriteConcernError = function() {
return bulkResult.writeConcernErrors.length > 0;
- }
+ };
this.getWriteConcernError = function() {
if(bulkResult.writeConcernErrors.length == 0) {
@@ -284,30 +284,30 @@ var _bulk_api_module = (function() {
return new WriteConcernError({ errmsg : errmsg, code : WRITE_CONCERN_FAILED });
}
- }
+ };
/**
* @return {string}
*/
this.tojson = function(indent, nolint) {
return tojson(bulkResult, indent, nolint);
- }
+ };
this.toString = function() {
// Suppress all output for the write concern w:0, since the client doesn't care.
if(writeConcern && writeConcern.w == 0) {
- return "BulkWriteResult(" + tojson({}) + ")";;
+ return "BulkWriteResult(" + tojson({}) + ")";
}
return "BulkWriteResult(" + this.tojson() + ")";
- }
+ };
this.shellPrint = function() {
return this.toString();
- }
+ };
this.hasErrors = function() {
return this.hasWriteErrors() || this.hasWriteConcernError();
- }
+ };
this.toError = function() {
if (this.hasErrors()) {
@@ -337,7 +337,7 @@ var _bulk_api_module = (function() {
else {
throw Error("batch was successful, cannot create BulkWriteError");
}
- }
+ };
/**
* @return {WriteResult} the simplified results condensed into one.
@@ -346,7 +346,7 @@ var _bulk_api_module = (function() {
if(singleBatchType == null) throw Error(
"Cannot output single WriteResult from multiple batch result");
return new WriteResult(bulkResult, singleBatchType, writeConcern);
- }
+ };
};
/**
@@ -368,13 +368,13 @@ var _bulk_api_module = (function() {
this.toString = function() {
return "BulkWriteError(" + this.tojson() + ")";
- }
+ };
this.stack = this.toString() + "\n" + (new Error().stack);
this.toResult = function() {
return new BulkWriteResult(bulkResult, singleBatchType, writeConcern);
- }
- }
+ };
+ };
BulkWriteError.prototype = new Error();
BulkWriteError.prototype.constructor = BulkWriteError;
@@ -390,7 +390,7 @@ var _bulk_api_module = (function() {
, nRemoved: 0
, upserted: []
};
- }
+ };
/**
* Wraps a command error
@@ -411,16 +411,16 @@ var _bulk_api_module = (function() {
*/
this.tojson = function(indent, nolint) {
return tojson(commandError, indent, nolint);
- }
+ };
this.toString = function() {
return "WriteCommandError(" + this.tojson() + ")";
- }
+ };
this.stack = this.toString() + "\n" + (new Error().stack);
this.shellPrint = function() {
return this.toString();
- }
+ };
this.toSingleResult = function() {
// This is *only* safe to do with a WriteCommandError from the bulk api when the bulk is
@@ -428,8 +428,8 @@ var _bulk_api_module = (function() {
var bulkResult = getEmptyBulkResult();
bulkResult.writeErrors.push({ code : this.code, index : 0, errmsg : this.errmsg });
return new BulkWriteResult(bulkResult, NONE).toSingleResult();
- }
- }
+ };
+ };
WriteCommandError.prototype = new Error();
WriteCommandError.prototype.constructor = WriteCommandError;
@@ -449,23 +449,23 @@ var _bulk_api_module = (function() {
// Define access methods
this.getOperation = function() {
return err.op;
- }
+ };
/**
* @return {string}
*/
this.tojson = function(indent, nolint) {
return tojson(err, indent, nolint);
- }
+ };
this.toString = function() {
return "WriteError(" + tojson(err) + ")";
- }
+ };
this.shellPrint = function() {
return this.toString();
- }
- }
+ };
+ };
/**
* Wraps a write concern error
@@ -483,16 +483,16 @@ var _bulk_api_module = (function() {
*/
this.tojson = function(indent, nolint) {
return tojson(err, indent, nolint);
- }
+ };
this.toString = function() {
return "WriteConcernError(" + tojson(err) + ")";
- }
+ };
this.shellPrint = function() {
return this.toString();
- }
- }
+ };
+ };
/**
* Keeps the state of an unordered batch so we can rewrite the results
@@ -502,7 +502,7 @@ var _bulk_api_module = (function() {
this.originalZeroIndex = originalZeroIndex;
this.batchType = batchType;
this.operations = [];
- }
+ };
/**
* Wraps a legacy operation so we can correctly rewrite its error
@@ -511,7 +511,7 @@ var _bulk_api_module = (function() {
this.batchType = batchType;
this.index = index;
this.operation = operation;
- }
+ };
/***********************************************************
* Wraps the operations done for the batch
@@ -556,7 +556,7 @@ var _bulk_api_module = (function() {
return counter;
}
});
- }
+ };
defineBatchTypeCounter(this, "nInsertOps", INSERT);
defineBatchTypeCounter(this, "nUpdateOps", UPDATE);
@@ -565,7 +565,7 @@ var _bulk_api_module = (function() {
// Convert bulk into string
this.toString = function() {
return this.tojson();
- }
+ };
this.tojson = function() {
return tojson({
@@ -573,12 +573,12 @@ var _bulk_api_module = (function() {
, nUpdateOps: this.nUpdateOps
, nRemoveOps: this.nRemoveOps
, nBatches: batches.length + (currentBatch == null ? 0 : 1)
- })
- }
+ });
+ };
this.getOperations = function() {
return batches;
- }
+ };
var finalizeBatch = function(newDocType) {
// Save the batch to the execution stack
@@ -663,7 +663,7 @@ var _bulk_api_module = (function() {
, u: updateDocument
, multi: true
, upsert: upsert
- }
+ };
// Clear out current Op
currentOp = null;
@@ -682,7 +682,7 @@ var _bulk_api_module = (function() {
, u: updateDocument
, multi: false
, upsert: upsert
- }
+ };
// Clear out current Op
currentOp = null;
@@ -707,7 +707,7 @@ var _bulk_api_module = (function() {
var document = {
q: currentOp.selector
, limit: 1
- }
+ };
// Clear out current Op
currentOp = null;
@@ -722,14 +722,14 @@ var _bulk_api_module = (function() {
var document = {
q: currentOp.selector
, limit: 0
- }
+ };
// Clear out current Op
currentOp = null;
// Add the remove document to the list
return addToOperationsList(REMOVE, document);
}
- }
+ };
//
// Start of update and remove operations
@@ -738,11 +738,11 @@ var _bulk_api_module = (function() {
// Save a current selector
currentOp = {
selector: selector
- }
+ };
// Return the find Operations
return findOperations;
- }
+ };
//
// Merge write command result into aggregated results object
@@ -809,7 +809,7 @@ var _bulk_api_module = (function() {
if(result.writeConcernError) {
bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError));
}
- }
+ };
//
// Constructs the write batch command.
@@ -818,7 +818,7 @@ var _bulk_api_module = (function() {
// Generate the right update
if(batch.batchType == UPDATE) {
- cmd = { update: coll.getName(), updates: batch.operations, ordered: ordered }
+ cmd = { update: coll.getName(), updates: batch.operations, ordered: ordered };
} else if(batch.batchType == INSERT) {
var transformedInserts = [];
batch.operations.forEach(function(insertDoc) {
@@ -826,9 +826,9 @@ var _bulk_api_module = (function() {
});
batch.operations = transformedInserts;
- cmd = { insert: coll.getName(), documents: batch.operations, ordered: ordered }
+ cmd = { insert: coll.getName(), documents: batch.operations, ordered: ordered };
} else if(batch.batchType == REMOVE) {
- cmd = { delete: coll.getName(), deletes: batch.operations, ordered: ordered }
+ cmd = { delete: coll.getName(), deletes: batch.operations, ordered: ordered };
}
// If we have a write concern
@@ -837,7 +837,7 @@ var _bulk_api_module = (function() {
}
return cmd;
- }
+ };
//
// Execute the batch
@@ -861,7 +861,7 @@ var _bulk_api_module = (function() {
// Merge the results
mergeBatchResults(batch, bulkResult, result);
- }
+ };
// Execute a single legacy op
var executeLegacyOp = function(_legacyOp) {
@@ -894,7 +894,7 @@ var _bulk_api_module = (function() {
_legacyOp.operation.q,
single);
}
- }
+ };
/**
* Parses the getLastError response and properly sets the write errors and
@@ -965,7 +965,7 @@ var _bulk_api_module = (function() {
extractedErr.unknownError = {
code: code
, errmsg: errMsg
- }
+ };
}
else if (err != '') {
extractedErr.writeError = {
@@ -1110,7 +1110,7 @@ var _bulk_api_module = (function() {
// Merge the results
mergeBatchResults(batch, bulkResult, batchResult);
- }
+ };
//
// Execute the batch
@@ -1163,7 +1163,7 @@ var _bulk_api_module = (function() {
}
return typedResult;
- }
+ };
// Generate an explain command for the bulk operation. Currently we only support single batches
// of size 1, which must be either delete or update.
@@ -1181,8 +1181,8 @@ var _bulk_api_module = (function() {
var explainBatch = batches[0];
var writeCmd = buildBatchCmd(explainBatch);
return {"explain": writeCmd, "verbosity": verbosity};
- }
- }
+ };
+ };
//
// Exports
diff --git a/src/mongo/shell/collection.js b/src/mongo/shell/collection.js
index 81b2ec98dd6..b23fd91d2d1 100644
--- a/src/mongo/shell/collection.js
+++ b/src/mongo/shell/collection.js
@@ -10,7 +10,7 @@ if ( ( typeof DBCollection ) == "undefined" ){
this._fullName = fullName;
this.verify();
- }
+ };
}
DBCollection.prototype.verify = function(){
@@ -22,11 +22,11 @@ DBCollection.prototype.verify = function(){
assert( this._mongo , "no mongo in DBCollection" );
assert( this.getMongo() , "no mongo from getMongo()" );
-}
+};
DBCollection.prototype.getName = function(){
return this._shortName;
-}
+};
DBCollection.prototype.help = function () {
var shortName = this.getName();
@@ -82,7 +82,7 @@ DBCollection.prototype.help = function () {
print("\tdb." + shortName + ".update( query, object[, upsert_bool, multi_bool] ) - instead of two flags, you can pass an object with fields: upsert, multi");
print("\tdb." + shortName + ".updateOne( filter, update, <optional params> ) - update the first matching document, optional parameters are: upsert, w, wtimeout, j");
print("\tdb." + shortName + ".updateMany( filter, update, <optional params> ) - update all matching documents, optional parameters are: upsert, w, wtimeout, j");
- print("\tdb." + shortName + ".validate( <full> ) - SLOW");;
+ print("\tdb." + shortName + ".validate( <full> ) - SLOW");
print("\tdb." + shortName + ".getShardVersion() - only for use with sharding");
print("\tdb." + shortName + ".getShardDistribution() - prints statistics about data distribution in the cluster");
print("\tdb." + shortName + ".getSplitKeysForChunks( <maxChunkSize> ) - calculates split points over all chunks and returns splitter function");
@@ -92,17 +92,17 @@ DBCollection.prototype.help = function () {
// print("\tdb." + shortName + ".getDiskStorageStats({...}) - prints a summary of disk usage statistics");
// print("\tdb." + shortName + ".getPagesInRAM({...}) - prints a summary of storage pages currently in physical memory");
return __magicNoPrint;
-}
+};
DBCollection.prototype.getFullName = function(){
return this._fullName;
-}
+};
DBCollection.prototype.getMongo = function(){
return this._db.getMongo();
-}
+};
DBCollection.prototype.getDB = function(){
return this._db;
-}
+};
DBCollection.prototype._makeCommand = function (cmd, params) {
var c = {};
@@ -110,14 +110,14 @@ DBCollection.prototype._makeCommand = function (cmd, params) {
if ( params )
Object.extend(c, params);
return c;
-}
+};
DBCollection.prototype._dbCommand = function( cmd , params ){
if (typeof( cmd ) === "object")
return this._db._dbCommand(cmd, {}, this.getQueryOptions());
return this._db._dbCommand(this._makeCommand(cmd, params), {}, this.getQueryOptions());
-}
+};
// Like _dbCommand, but applies $readPreference
DBCollection.prototype._dbReadCommand = function( cmd , params ){
@@ -125,7 +125,7 @@ DBCollection.prototype._dbReadCommand = function( cmd , params ){
return this._db._dbReadCommand( cmd , {}, this.getQueryOptions());
return this._db._dbReadCommand(this._makeCommand(cmd, params), {}, this.getQueryOptions());
-}
+};
DBCollection.prototype.runCommand = DBCollection.prototype._dbCommand;
@@ -155,7 +155,7 @@ DBCollection.prototype._massageObject = function( q ){
throw Error( "don't know how to massage : " + type );
-}
+};
DBCollection.prototype._validateObject = function( o ){
@@ -167,7 +167,7 @@ DBCollection.prototype._validateObject = function( o ){
if ( o._ensureSpecial && o._checkModify )
throw Error( "can't save a DBQuery object" );
-}
+};
DBCollection._allowedFields = { $id : 1 , $ref : 1 , $db : 1 };
@@ -202,7 +202,7 @@ DBCollection.prototype.find = function( query , fields , limit , skip, batchSize
}
return cursor;
-}
+};
DBCollection.prototype.findOne = function( query , fields, options, readConcern ){
var cursor = this.find(query, fields, -1 /* limit */, 0 /* skip*/,
@@ -219,7 +219,7 @@ DBCollection.prototype.findOne = function( query , fields, options, readConcern
if ( ret.$err )
throw _getErrorWithCode(ret, "error " + tojson(ret));
return ret;
-}
+};
DBCollection.prototype.insert = function( obj , options, _allow_dot ){
if ( ! obj )
@@ -350,7 +350,7 @@ DBCollection.prototype._parseRemove = function( t , justOne ) {
}
return {"query": query, "justOne": justOne, "wc": wc};
-}
+};
DBCollection.prototype.remove = function( t , justOne ){
var parsed = this._parseRemove(t, justOne);
@@ -399,7 +399,7 @@ DBCollection.prototype.remove = function( t , justOne ){
this._printExtraInfo("Removed", startTime);
return result;
-}
+};
DBCollection.prototype._validateUpdateDoc = function(doc) {
// Hidden property for testing purposes.
@@ -454,7 +454,7 @@ DBCollection.prototype._parseUpdate = function( query , obj , upsert , multi ){
"upsert": upsert,
"multi": multi,
"wc": wc};
-}
+};
DBCollection.prototype.update = function( query , obj , upsert , multi ){
var parsed = this._parseUpdate(query, obj, upsert, multi);
@@ -523,7 +523,7 @@ DBCollection.prototype.save = function( obj , opts ){
else {
return this.update( { _id : obj._id } , obj , Object.merge({ upsert:true }, opts));
}
-}
+};
DBCollection.prototype._genIndexName = function( keys ){
var name = "";
@@ -539,7 +539,7 @@ DBCollection.prototype._genIndexName = function( keys ){
name += v;
}
return name;
-}
+};
DBCollection.prototype._indexSpec = function( keys, options ) {
var ret = { ns : this._fullName , key : keys , name : this._genIndexName( keys ) };
@@ -580,11 +580,11 @@ DBCollection.prototype._indexSpec = function( keys, options ) {
}
return ret;
-}
+};
DBCollection.prototype.createIndex = function(keys , options) {
return this.createIndexes([keys], options);
-}
+};
DBCollection.prototype.createIndexes = function(keys, options) {
var indexSpecs = Array(keys.length);
@@ -616,7 +616,7 @@ DBCollection.prototype.createIndexes = function(keys, options) {
else {
this._db.getCollection("system.indexes").insert(indexSpecs, 0, true);
}
-}
+};
DBCollection.prototype.ensureIndex = function( keys , options ){
var result = this.createIndex(keys, options);
@@ -630,11 +630,11 @@ DBCollection.prototype.ensureIndex = function( keys , options ){
return err;
}
// nothing returned on success
-}
+};
DBCollection.prototype.reIndex = function() {
return this._db.runCommand({ reIndex: this.getName() });
-}
+};
DBCollection.prototype.dropIndexes = function(){
if ( arguments.length )
@@ -649,7 +649,7 @@ DBCollection.prototype.dropIndexes = function(){
return res;
throw _getErrorWithCode(res, "error dropping indexes : " + tojson(res));
-}
+};
DBCollection.prototype.drop = function(){
@@ -662,7 +662,7 @@ DBCollection.prototype.drop = function(){
throw _getErrorWithCode(ret, "drop failed: " + tojson(ret));
}
return true;
-}
+};
DBCollection.prototype.findAndModify = function(args){
var cmd = { findandmodify: this.getName() };
@@ -678,13 +678,13 @@ DBCollection.prototype.findAndModify = function(args){
throw _getErrorWithCode(ret, "findAndModifyFailed failed: " + tojson(ret));
}
return ret.value;
-}
+};
DBCollection.prototype.renameCollection = function( newName , dropTarget ){
return this._db._adminCommand( { renameCollection : this._fullName ,
to : this._db._name + "." + newName ,
- dropTarget : dropTarget } )
-}
+ dropTarget : dropTarget } );
+};
// Display verbose information about the operation
DBCollection.prototype._printExtraInfo = function(action, startTime) {
@@ -706,13 +706,13 @@ DBCollection.prototype._printExtraInfo = function(action, startTime) {
// hack for inserted because res.n is 0
info += action != "Inserted" ? res.n : 1;
if (res.n > 0 && res.updatedExisting != undefined)
- info += " " + (res.updatedExisting ? "existing" : "new")
+ info += " " + (res.updatedExisting ? "existing" : "new");
info += " record(s)";
var time = new Date().getTime() - startTime;
info += " in " + time + "ms";
print(info);
}
-}
+};
DBCollection.prototype.validate = function(full) {
var cmd = { validate: this.getName() };
@@ -744,7 +744,7 @@ DBCollection.prototype.validate = function(full) {
}
return res;
-}
+};
/**
* Invokes the storageDetails command to provide aggregate and (if requested) detailed information
@@ -760,7 +760,7 @@ DBCollection.prototype.diskStorageStats = function(opt) {
print("this command requires starting mongod with --enableExperimentalStorageDetailsCmd");
}
return res;
-}
+};
// Refer to diskStorageStats
DBCollection.prototype.getDiskStorageStats = function(params) {
@@ -820,7 +820,7 @@ DBCollection.prototype.getDiskStorageStats = function(params) {
printExtent(stats, "range " + stats.range);
}
-}
+};
/**
* Invokes the storageDetails command to report the percentage of virtual memory pages of the
@@ -836,7 +836,7 @@ DBCollection.prototype.pagesInRAM = function(opt) {
print("this command requires starting mongod with --enableExperimentalStorageDetailsCmd");
}
return res;
-}
+};
// Refer to pagesInRAM
DBCollection.prototype.getPagesInRAM = function(params) {
@@ -851,7 +851,7 @@ DBCollection.prototype.getPagesInRAM = function(params) {
return "size".pad(8) + " " +
_barFormat([ [data.inMem, '='] ], BAR_WIDTH) + " " +
data.inMem.toPercentStr().pad(7);
- }
+ };
var printExtent = function(ex, rng) {
print("--- extent " + rng + " ---");
@@ -879,7 +879,7 @@ DBCollection.prototype.getPagesInRAM = function(params) {
print(line + "]");
print();
}
- }
+ };
if (stats.extents) {
print("--- extent overview ---\n");
@@ -900,19 +900,19 @@ DBCollection.prototype.getPagesInRAM = function(params) {
} else {
printExtent(stats, "range " + stats.range);
}
-}
+};
DBCollection.prototype.getShardVersion = function(){
return this._db._adminCommand( { getShardVersion : this._fullName } );
-}
+};
DBCollection.prototype._getIndexesSystemIndexes = function(filter){
var si = this.getDB().getCollection( "system.indexes" );
var query = { ns : this.getFullName() };
if (filter)
- query = Object.extend(query, filter)
+ query = Object.extend(query, filter);
return si.find( query ).toArray();
-}
+};
DBCollection.prototype._getIndexesCommand = function(filter){
var res = this.runCommand( "listIndexes", filter );
@@ -937,7 +937,7 @@ DBCollection.prototype._getIndexesCommand = function(filter){
}
return new DBCommandCursor(this._mongo, res).toArray();
-}
+};
DBCollection.prototype.getIndexes = function(filter){
var res = this._getIndexesCommand(filter);
@@ -945,7 +945,7 @@ DBCollection.prototype.getIndexes = function(filter){
return res;
}
return this._getIndexesSystemIndexes(filter);
-}
+};
DBCollection.prototype.getIndices = DBCollection.prototype.getIndexes;
DBCollection.prototype.getIndexSpecs = DBCollection.prototype.getIndexes;
@@ -956,7 +956,7 @@ DBCollection.prototype.getIndexKeys = function(){
return i.key;
}
);
-}
+};
DBCollection.prototype.hashAllDocs = function() {
@@ -967,7 +967,7 @@ DBCollection.prototype.hashAllDocs = function() {
assert( hash );
assert( typeof(hash) == "string" );
return hash;
-}
+};
/**
* <p>Drop a specified index.</p>
@@ -987,7 +987,7 @@ DBCollection.prototype.dropIndex = function(index) {
assert(index, "need to specify index to dropIndex" );
var res = this._dbCommand( "deleteIndexes", { index: index } );
return res;
-}
+};
DBCollection.prototype.copyTo = function( newName ){
return this.getDB().eval(
@@ -1007,11 +1007,11 @@ DBCollection.prototype.copyTo = function( newName ){
return count;
} , this.getName() , newName
);
-}
+};
DBCollection.prototype.getCollection = function( subName ){
return this._db.getCollection( this._shortName + "." + subName );
-}
+};
/**
* scale: The scale at which to deliver results. Unless specified, this command returns all data
@@ -1075,15 +1075,15 @@ DBCollection.prototype.stats = function(args) {
}
return res;
-}
+};
DBCollection.prototype.dataSize = function(){
return this.stats().size;
-}
+};
DBCollection.prototype.storageSize = function(){
return this.stats().storageSize;
-}
+};
DBCollection.prototype.totalIndexSize = function( verbose ){
var stats = this.stats();
@@ -1093,7 +1093,7 @@ DBCollection.prototype.totalIndexSize = function( verbose ){
}
}
return stats.totalIndexSize;
-}
+};
DBCollection.prototype.totalSize = function(){
@@ -1103,14 +1103,14 @@ DBCollection.prototype.totalSize = function(){
total += totalIndexSize;
}
return total;
-}
+};
DBCollection.prototype.convertToCapped = function( bytes ){
if ( ! bytes )
throw Error("have to specify # of bytes");
- return this._dbCommand( { convertToCapped : this._shortName , size : bytes } )
-}
+ return this._dbCommand( { convertToCapped : this._shortName , size : bytes } );
+};
DBCollection.prototype.exists = function(){
var res = this._db.runCommand( "listCollections",
@@ -1127,12 +1127,12 @@ DBCollection.prototype.exists = function(){
}
throw _getErrorWithCode(res, "listCollections failed: " + tojson(res));
-}
+};
DBCollection.prototype.isCapped = function(){
var e = this.exists();
return ( e && e.options && e.options.capped ) ? true : false;
-}
+};
//
// CRUD specification aggregation cursor extension
@@ -1140,8 +1140,8 @@ DBCollection.prototype.isCapped = function(){
DBCollection.prototype.aggregate = function(pipeline, aggregateOptions) {
if (!(pipeline instanceof Array)) {
// support legacy varargs form. (Also handles db.foo.aggregate())
- pipeline = argumentsToArray(arguments)
- aggregateOptions = {}
+ pipeline = argumentsToArray(arguments);
+ aggregateOptions = {};
} else if (aggregateOptions === undefined) {
aggregateOptions = {};
}
@@ -1219,17 +1219,17 @@ DBCollection.prototype.aggregate = function(pipeline, aggregateOptions) {
}
return res;
-}
+};
DBCollection.prototype.group = function( params ){
params.ns = this._shortName;
return this._db.group( params );
-}
+};
DBCollection.prototype.groupcmd = function( params ){
params.ns = this._shortName;
return this._db.groupcmd( params );
-}
+};
MapReduceResult = function( db , o ){
Object.extend( this , o );
@@ -1239,23 +1239,23 @@ MapReduceResult = function( db , o ){
if ( this.result != null ) {
this._coll = this._db.getCollection( this.result );
}
-}
+};
MapReduceResult.prototype._simpleKeys = function(){
return this._o;
-}
+};
MapReduceResult.prototype.find = function(){
if ( this.results )
return this.results;
return DBCollection.prototype.find.apply( this._coll , arguments );
-}
+};
MapReduceResult.prototype.drop = function(){
if ( this._coll ) {
return this._coll.drop();
}
-}
+};
/**
* just for debugging really
@@ -1265,20 +1265,20 @@ MapReduceResult.prototype.convertToSingleObject = function(){
var it = this.results != null ? this.results : this._coll.find();
it.forEach( function(a){ z[a._id] = a.value; } );
return z;
-}
+};
DBCollection.prototype.convertToSingleObject = function(valueField){
var z = {};
this.find().forEach( function(a){ z[a._id] = a[valueField]; } );
return z;
-}
+};
/**
* @param optional object of optional fields;
*/
DBCollection.prototype.mapReduce = function( map , reduce , optionsOrOutString ){
var c = { mapreduce : this._shortName , map : map , reduce : reduce };
- assert( optionsOrOutString , "need to supply an optionsOrOutString" )
+ assert( optionsOrOutString , "need to supply an optionsOrOutString" );
if ( typeof( optionsOrOutString ) == "string" )
c["out"] = optionsOrOutString;
@@ -1301,15 +1301,15 @@ DBCollection.prototype.mapReduce = function( map , reduce , optionsOrOutString )
}
return new MapReduceResult( this._db , raw );
-}
+};
DBCollection.prototype.toString = function(){
return this.getFullName();
-}
+};
DBCollection.prototype.toString = function(){
return this.getFullName();
-}
+};
DBCollection.prototype.tojson = DBCollection.prototype.toString;
@@ -1327,7 +1327,7 @@ DBCollection.autocomplete = function(obj){
ret.push(c.slice(obj.getName().length+1));
}
return ret;
-}
+};
// Sharding additions
@@ -1357,185 +1357,185 @@ true
DBCollection.prototype.getShardDistribution = function(){
- var stats = this.stats()
+ var stats = this.stats();
if( ! stats.sharded ){
- print( "Collection " + this + " is not sharded." )
- return
+ print( "Collection " + this + " is not sharded." );
+ return;
}
- var config = this.getMongo().getDB("config")
+ var config = this.getMongo().getDB("config");
- var numChunks = 0
+ var numChunks = 0;
for( var shard in stats.shards ){
- var shardDoc = config.shards.findOne({ _id : shard })
+ var shardDoc = config.shards.findOne({ _id : shard });
- print( "\nShard " + shard + " at " + shardDoc.host )
+ print( "\nShard " + shard + " at " + shardDoc.host );
- var shardStats = stats.shards[ shard ]
+ var shardStats = stats.shards[ shard ];
- var chunks = config.chunks.find({ _id : sh._collRE( this ), shard : shard }).toArray()
+ var chunks = config.chunks.find({ _id : sh._collRE( this ), shard : shard }).toArray();
- numChunks += chunks.length
+ numChunks += chunks.length;
- var estChunkData = shardStats.size / chunks.length
- var estChunkCount = Math.floor( shardStats.count / chunks.length )
+ var estChunkData = shardStats.size / chunks.length;
+ var estChunkCount = Math.floor( shardStats.count / chunks.length );
print( " data : " + sh._dataFormat( shardStats.size ) +
" docs : " + shardStats.count +
- " chunks : " + chunks.length )
- print( " estimated data per chunk : " + sh._dataFormat( estChunkData ) )
- print( " estimated docs per chunk : " + estChunkCount )
+ " chunks : " + chunks.length );
+ print( " estimated data per chunk : " + sh._dataFormat( estChunkData ) );
+ print( " estimated docs per chunk : " + estChunkCount );
}
- print( "\nTotals" )
+ print( "\nTotals" );
print( " data : " + sh._dataFormat( stats.size ) +
" docs : " + stats.count +
- " chunks : " + numChunks )
+ " chunks : " + numChunks );
for( var shard in stats.shards ){
- var shardStats = stats.shards[ shard ]
+ var shardStats = stats.shards[ shard ];
- var estDataPercent = Math.floor( shardStats.size / stats.size * 10000 ) / 100
- var estDocPercent = Math.floor( shardStats.count / stats.count * 10000 ) / 100
+ var estDataPercent = Math.floor( shardStats.size / stats.size * 10000 ) / 100;
+ var estDocPercent = Math.floor( shardStats.count / stats.count * 10000 ) / 100;
print( " Shard " + shard + " contains " + estDataPercent + "% data, " + estDocPercent + "% docs in cluster, " +
- "avg obj size on shard : " + sh._dataFormat( stats.shards[ shard ].avgObjSize ) )
+ "avg obj size on shard : " + sh._dataFormat( stats.shards[ shard ].avgObjSize ) );
}
- print( "\n" )
+ print( "\n" );
-}
+};
DBCollection.prototype.getSplitKeysForChunks = function( chunkSize ){
- var stats = this.stats()
+ var stats = this.stats();
if( ! stats.sharded ){
- print( "Collection " + this + " is not sharded." )
- return
+ print( "Collection " + this + " is not sharded." );
+ return;
}
- var config = this.getMongo().getDB("config")
+ var config = this.getMongo().getDB("config");
if( ! chunkSize ){
- chunkSize = config.settings.findOne({ _id : "chunksize" }).value
- print( "Chunk size not set, using default of " + chunkSize + "MB" )
+ chunkSize = config.settings.findOne({ _id : "chunksize" }).value;
+ print( "Chunk size not set, using default of " + chunkSize + "MB" );
}
else{
- print( "Using chunk size of " + chunkSize + "MB" )
+ print( "Using chunk size of " + chunkSize + "MB" );
}
- var shardDocs = config.shards.find().toArray()
+ var shardDocs = config.shards.find().toArray();
- var allSplitPoints = {}
- var numSplits = 0
+ var allSplitPoints = {};
+ var numSplits = 0;
for( var i = 0; i < shardDocs.length; i++ ){
- var shardDoc = shardDocs[i]
- var shard = shardDoc._id
- var host = shardDoc.host
- var sconn = new Mongo( host )
+ var shardDoc = shardDocs[i];
+ var shard = shardDoc._id;
+ var host = shardDoc.host;
+ var sconn = new Mongo( host );
- var chunks = config.chunks.find({ _id : sh._collRE( this ), shard : shard }).toArray()
+ var chunks = config.chunks.find({ _id : sh._collRE( this ), shard : shard }).toArray();
- print( "\nGetting split points for chunks on shard " + shard + " at " + host )
+ print( "\nGetting split points for chunks on shard " + shard + " at " + host );
- var splitPoints = []
+ var splitPoints = [];
for( var j = 0; j < chunks.length; j++ ){
- var chunk = chunks[j]
- var result = sconn.getDB("admin").runCommand({ splitVector : this + "", min : chunk.min, max : chunk.max, maxChunkSize : chunkSize })
+ var chunk = chunks[j];
+ var result = sconn.getDB("admin").runCommand({ splitVector : this + "", min : chunk.min, max : chunk.max, maxChunkSize : chunkSize });
if( ! result.ok ){
- print( " Had trouble getting split keys for chunk " + sh._pchunk( chunk ) + " :\n" )
- printjson( result )
+ print( " Had trouble getting split keys for chunk " + sh._pchunk( chunk ) + " :\n" );
+ printjson( result );
}
else{
- splitPoints = splitPoints.concat( result.splitKeys )
+ splitPoints = splitPoints.concat( result.splitKeys );
if( result.splitKeys.length > 0 )
- print( " Added " + result.splitKeys.length + " split points for chunk " + sh._pchunk( chunk ) )
+ print( " Added " + result.splitKeys.length + " split points for chunk " + sh._pchunk( chunk ) );
}
}
- print( "Total splits for shard " + shard + " : " + splitPoints.length )
+ print( "Total splits for shard " + shard + " : " + splitPoints.length );
- numSplits += splitPoints.length
- allSplitPoints[ shard ] = splitPoints
+ numSplits += splitPoints.length;
+ allSplitPoints[ shard ] = splitPoints;
}
// Get most recent migration
- var migration = config.changelog.find({ what : /^move.*/ }).sort({ time : -1 }).limit( 1 ).toArray()
+ var migration = config.changelog.find({ what : /^move.*/ }).sort({ time : -1 }).limit( 1 ).toArray();
if( migration.length == 0 )
- print( "\nNo migrations found in changelog." )
+ print( "\nNo migrations found in changelog." );
else {
- migration = migration[0]
- print( "\nMost recent migration activity was on " + migration.ns + " at " + migration.time )
+ migration = migration[0];
+ print( "\nMost recent migration activity was on " + migration.ns + " at " + migration.time );
}
- var admin = this.getMongo().getDB("admin")
- var coll = this
+ var admin = this.getMongo().getDB("admin");
+ var coll = this;
var splitFunction = function(){
// Turn off the balancer, just to be safe
- print( "Turning off balancer..." )
- config.settings.update({ _id : "balancer" }, { $set : { stopped : true } }, true )
+ print( "Turning off balancer..." );
+ config.settings.update({ _id : "balancer" }, { $set : { stopped : true } }, true );
print( "Sleeping for 30s to allow balancers to detect change. To be extra safe, check config.changelog" +
- " for recent migrations." )
- sleep( 30000 )
+ " for recent migrations." );
+ sleep( 30000 );
for( var shard in allSplitPoints ){
for( var i = 0; i < allSplitPoints[ shard ].length; i++ ){
- var splitKey = allSplitPoints[ shard ][i]
- print( "Splitting at " + tojson( splitKey ) )
- printjson( admin.runCommand({ split : coll + "", middle : splitKey }) )
+ var splitKey = allSplitPoints[ shard ][i];
+ print( "Splitting at " + tojson( splitKey ) );
+ printjson( admin.runCommand({ split : coll + "", middle : splitKey }) );
}
}
- print( "Turning the balancer back on." )
- config.settings.update({ _id : "balancer" }, { $set : { stopped : false } } )
- sleep( 1 )
- }
+ print( "Turning the balancer back on." );
+ config.settings.update({ _id : "balancer" }, { $set : { stopped : false } } );
+ sleep( 1 );
+ };
- splitFunction.getSplitPoints = function(){ return allSplitPoints; }
+ splitFunction.getSplitPoints = function(){ return allSplitPoints; };
print( "\nGenerated " + numSplits + " split keys, run output function to perform splits.\n" +
" ex : \n" +
" > var splitter = <collection>.getSplitKeysForChunks()\n" +
- " > splitter() // Execute splits on cluster !\n" )
+ " > splitter() // Execute splits on cluster !\n" );
- return splitFunction
+ return splitFunction;
-}
+};
DBCollection.prototype.setSlaveOk = function( value ) {
if( value == undefined ) value = true;
this._slaveOk = value;
-}
+};
DBCollection.prototype.getSlaveOk = function() {
if (this._slaveOk != undefined) return this._slaveOk;
return this._db.getSlaveOk();
-}
+};
DBCollection.prototype.getQueryOptions = function() {
// inherit this method from DB but use apply so
// that slaveOk will be set if is overridden on this DBCollection
return this._db.getQueryOptions.apply(this, arguments);
-}
+};
/**
* Returns a PlanCache for the collection.
*/
DBCollection.prototype.getPlanCache = function() {
return new PlanCache( this );
-}
+};
// Overrides connection-level settings.
//
@@ -1607,7 +1607,7 @@ DBCollection.prototype.count = function(query, options) {
// Return the result of the find
return query.count(true);
-}
+};
/**
* The distinct command returns returns a list of distinct values for the given key across a collection.
@@ -1651,11 +1651,11 @@ DBCollection.prototype.distinct = function(keyString, query, options){
}
return res.values;
-}
+};
DBCollection.prototype._distinct = function( keyString , query ){
return this._dbReadCommand( { distinct : this._shortName , key : keyString , query : query || {} } );
-}
+};
/**
* PlanCache
@@ -1665,7 +1665,7 @@ DBCollection.prototype._distinct = function( keyString , query ){
if ( ( typeof PlanCache ) == "undefined" ){
PlanCache = function( collection ){
this._collection = collection;
- }
+ };
}
/**
@@ -1674,7 +1674,7 @@ if ( ( typeof PlanCache ) == "undefined" ){
*/
PlanCache.prototype.getName = function(){
return this._collection.getName();
-}
+};
/**
@@ -1682,7 +1682,7 @@ PlanCache.prototype.getName = function(){
*/
PlanCache.prototype.toString = function(){
return "PlanCache for collection " + this.getName() + '. Type help() for more info.';
-}
+};
PlanCache.prototype.shellPrint = PlanCache.prototype.toString;
@@ -1702,7 +1702,7 @@ PlanCache.prototype.help = function () {
print("\tdb." + shortName + ".getPlanCache().getPlansByQuery(query[, projection, sort]) - " +
"displays the cached plans for a query shape");
return __magicNoPrint;
-}
+};
/**
* Internal function to parse query shape.
@@ -1734,7 +1734,7 @@ PlanCache.prototype._parseQueryShape = function(query, projection, sort) {
throw new Error("cannot pass DBQuery with sort");
}
- var queryObj = query._query["query"] || {}
+ var queryObj = query._query["query"] || {};
projection = query._fields || {};
sort = query._query["orderby"] || {};
// Overwrite DBQuery with the BSON query.
@@ -1747,7 +1747,7 @@ PlanCache.prototype._parseQueryShape = function(query, projection, sort) {
sort: sort == undefined ? {} : sort,
};
return shape;
-}
+};
/**
* Internal function to run command.
@@ -1758,14 +1758,14 @@ PlanCache.prototype._runCommandThrowOnError = function(cmd, params) {
throw new Error(res.errmsg);
}
return res;
-}
+};
/**
* Lists query shapes in a collection.
*/
PlanCache.prototype.listQueryShapes = function() {
return this._runCommandThrowOnError("planCacheListQueryShapes", {}).shapes;
-}
+};
/**
* Clears plan cache in a collection.
@@ -1773,7 +1773,7 @@ PlanCache.prototype.listQueryShapes = function() {
PlanCache.prototype.clear = function() {
this._runCommandThrowOnError("planCacheClear", {});
return;
-}
+};
/**
* List plans for a query shape.
@@ -1781,7 +1781,7 @@ PlanCache.prototype.clear = function() {
PlanCache.prototype.getPlansByQuery = function(query, projection, sort) {
return this._runCommandThrowOnError("planCacheListPlans",
this._parseQueryShape(query, projection, sort)).plans;
-}
+};
/**
* Drop query shape from the plan cache.
@@ -1789,4 +1789,4 @@ PlanCache.prototype.getPlansByQuery = function(query, projection, sort) {
PlanCache.prototype.clearPlansByQuery = function(query, projection, sort) {
this._runCommandThrowOnError("planCacheClear", this._parseQueryShape(query, projection, sort));
return;
-}
+};
diff --git a/src/mongo/shell/crud_api.js b/src/mongo/shell/crud_api.js
index 2e3e7b84be0..dcd1edf9854 100644
--- a/src/mongo/shell/crud_api.js
+++ b/src/mongo/shell/crud_api.js
@@ -22,7 +22,7 @@ DBCollection.prototype._createWriteConcern = function(options) {
}
return writeConcern;
-}
+};
/**
* @return {Object} a new document with an _id: ObjectId if _id is not present.
@@ -39,7 +39,7 @@ DBCollection.prototype.addIdIfNeeded = function(obj) {
}
return obj;
-}
+};
/**
* Perform a bulkWrite operation without a fluent API
@@ -112,7 +112,7 @@ DBCollection.prototype.bulkWrite = function(operations, options) {
operation = operation.upsert();
}
- operation.updateOne(op.updateOne.update)
+ operation.updateOne(op.updateOne.update);
} else if(op.updateMany) {
if(!op.updateMany.filter) {
throw new Error('updateMany bulkWrite operation expects the filter field');
@@ -128,7 +128,7 @@ DBCollection.prototype.bulkWrite = function(operations, options) {
operation = operation.upsert();
}
- operation.update(op.updateMany.update)
+ operation.update(op.updateMany.update);
} else if(op.replaceOne) {
if(!op.replaceOne.filter) {
throw new Error('replaceOne bulkWrite operation expects the filter field');
@@ -144,7 +144,7 @@ DBCollection.prototype.bulkWrite = function(operations, options) {
operation = operation.upsert();
}
- operation.replaceOne(op.replaceOne.replacement)
+ operation.replaceOne(op.replaceOne.replacement);
} else if(op.deleteOne) {
if(!op.deleteOne.filter) {
throw new Error('deleteOne bulkWrite operation expects the filter field');
@@ -183,7 +183,7 @@ DBCollection.prototype.bulkWrite = function(operations, options) {
// Return the result
return result;
-}
+};
/**
* Inserts a single document into MongoDB.
@@ -236,7 +236,7 @@ DBCollection.prototype.insertOne = function(document, options) {
// Return the result
return result;
-}
+};
/**
* Inserts an array of documents into MongoDB.
@@ -289,7 +289,7 @@ DBCollection.prototype.insertMany = function(documents, options) {
// Return the result
return result;
-}
+};
/**
* Delete a document on MongoDB
@@ -338,7 +338,7 @@ DBCollection.prototype.deleteOne = function(filter, options) {
result.deletedCount = r.nRemoved;
return result;
-}
+};
/**
* Delete multiple documents on MongoDB
@@ -387,7 +387,7 @@ DBCollection.prototype.deleteMany = function(filter, options) {
result.deletedCount = r.nRemoved;
return result;
-}
+};
/**
* Replace a document on MongoDB
@@ -456,7 +456,7 @@ DBCollection.prototype.replaceOne = function(filter, replacement, options) {
}
return result;
-}
+};
/**
* Update a single document on MongoDB
@@ -525,11 +525,11 @@ DBCollection.prototype.updateOne = function(filter, update, options) {
result.modifiedCount = (r.nModified != null) ? r.nModified : r.n;
if (r.getUpsertedIds().length > 0) {
- result.upsertedId = r.getUpsertedIdAt(0)._id
+ result.upsertedId = r.getUpsertedIdAt(0)._id;
}
return result;
-}
+};
/**
* Update multiple documents on MongoDB
@@ -598,11 +598,11 @@ DBCollection.prototype.updateMany = function(filter, update, options) {
result.modifiedCount = (r.nModified != null) ? r.nModified : r.n;
if (r.getUpsertedIds().length > 0) {
- result.upsertedId = r.getUpsertedIdAt(0)._id
+ result.upsertedId = r.getUpsertedIdAt(0)._id;
}
return result;
-}
+};
/**
* Find a document and delete it in one atomic operation,
@@ -643,7 +643,7 @@ DBCollection.prototype.findOneAndDelete = function(filter, options) {
// Execute findAndModify
return this.findAndModify(cmd);
-}
+};
/**
* Find a document and replace it in one atomic operation, requires a write lock for the duration of the operation.
@@ -697,7 +697,7 @@ DBCollection.prototype.findOneAndReplace = function(filter, replacement, options
// Execute findAndModify
return this.findAndModify(cmd);
-}
+};
/**
* Find a document and update it in one atomic operation, requires a write lock for the duration of the operation.
@@ -755,4 +755,4 @@ DBCollection.prototype.findOneAndUpdate = function(filter, update, options) {
// Execute findAndModify
return this.findAndModify(cmd);
-}
+};
diff --git a/src/mongo/shell/db.js b/src/mongo/shell/db.js
index d3b0fa73634..e17cfa36858 100644
--- a/src/mongo/shell/db.js
+++ b/src/mongo/shell/db.js
@@ -8,31 +8,31 @@ if (DB === undefined) {
DB = function( mongo , name ){
this._mongo = mongo;
this._name = name;
- }
+ };
}
DB.prototype.getMongo = function(){
assert( this._mongo , "why no mongo!" );
return this._mongo;
-}
+};
DB.prototype.getSiblingDB = function( name ){
return this.getMongo().getDB( name );
-}
+};
DB.prototype.getSisterDB = DB.prototype.getSiblingDB;
DB.prototype.getName = function(){
return this._name;
-}
+};
DB.prototype.stats = function(scale){
return this.runCommand( { dbstats : 1 , scale : scale } );
-}
+};
DB.prototype.getCollection = function( name ){
return new DBCollection( this._mongo , this , name , this._name + "." + name );
-}
+};
DB.prototype.commandHelp = function( name ){
var c = {};
@@ -42,7 +42,7 @@ DB.prototype.commandHelp = function( name ){
if ( ! res.ok )
throw _getErrorWithCode(res, res.errmsg);
return res.help;
-}
+};
// utility to attach readPreference if needed.
DB.prototype._attachReadPreferenceToCommand = function (cmdObj, readPref) {
@@ -112,7 +112,7 @@ DB.prototype.commandHelp = function( name ){
// runCommand uses this impl to actually execute the command
DB.prototype._runCommandImpl = function(name, obj, options){
return this.getMongo().runCommand(name, obj, options);
- }
+ };
DB.prototype.runCommand = function( obj, extra, queryOptions ){
var mergedObj = (typeof(obj) === "string") ? this._mergeCommandOptions(obj, extra) : obj;
@@ -147,7 +147,7 @@ DB.prototype.adminCommand = function( obj, extra ){
if ( this._name == "admin" )
return this.runCommand( obj, extra );
return this.getSiblingDB( "admin" ).runCommand( obj, extra );
-}
+};
DB.prototype._adminCommand = DB.prototype.adminCommand; // alias old name
@@ -229,7 +229,7 @@ DB.prototype.createCollection = function(name, opt) {
Object.extend(cmd, options);
return this._dbCommand(cmd);
-}
+};
/**
* @deprecated use getProfilingStatus
@@ -239,7 +239,7 @@ DB.prototype.createCollection = function(name, opt) {
DB.prototype.getProfilingLevel = function() {
var res = assert.commandWorked(this._dbCommand( { profile: -1 } ));
return res ? res.was : null;
-}
+};
/**
* @return the current profiling status
@@ -250,9 +250,9 @@ DB.prototype.getProfilingStatus = function() {
var res = this._dbCommand( { profile: -1 } );
if ( ! res.ok )
throw _getErrorWithCode(res, "profile command failed: " + tojson(res));
- delete res.ok
+ delete res.ok;
return res;
-}
+};
/**
@@ -264,7 +264,7 @@ DB.prototype.dropDatabase = function() {
if ( arguments.length )
throw Error("dropDatabase doesn't take arguments");
return this._dbCommand( { dropDatabase: 1 } );
-}
+};
/**
* Shuts down the database. Must be run while using the admin database.
@@ -300,7 +300,7 @@ DB.prototype.shutdownServer = function(opts) {
}
throw e;
}
-}
+};
/**
Clone database on another server to here.
@@ -320,7 +320,7 @@ DB.prototype.shutdownServer = function(opts) {
DB.prototype.cloneDatabase = function(from) {
assert( isString(from) && from.length );
return this._dbCommand( { clone: from } );
-}
+};
/**
@@ -346,7 +346,7 @@ DB.prototype.cloneCollection = function(from, collection, query) {
collection = this._name + "." + collection;
query = query || {};
return this._dbCommand( { cloneCollection:collection, from:from, query:query } );
-}
+};
/**
@@ -394,7 +394,7 @@ DB.prototype.copyDatabase = function(fromdb, todb, fromhost, username, password,
return this._adminCommand({ copydb:1, fromhost:fromhost, fromdb:fromdb, todb:todb,
username:username, nonce:n.nonce,
key:this.__pwHash(n.nonce, username, password) });
-}
+};
/**
Repair database.
@@ -403,7 +403,7 @@ DB.prototype.copyDatabase = function(fromdb, todb, fromhost, username, password,
*/
DB.prototype.repairDatabase = function() {
return this._dbCommand( { repairDatabase: 1 } );
-}
+};
DB.prototype.help = function() {
@@ -461,7 +461,7 @@ DB.prototype.help = function() {
print("\tdb.version() current version of the server");
return __magicNoPrint;
-}
+};
DB.prototype.printCollectionStats = function(scale) {
if (arguments.length > 1) {
@@ -486,7 +486,7 @@ DB.prototype.printCollectionStats = function(scale) {
print( "---" );
}
);
-}
+};
/**
* <p> Set profiling level for your db. Profiling gathers stats on query performance. </p>
@@ -516,7 +516,7 @@ DB.prototype.setProfilingLevel = function(level,slowms) {
if ( isNumber( slowms ) )
cmd["slowms"] = slowms;
return assert.commandWorked(this._dbCommand( cmd ));
-}
+};
/**
* @deprecated
@@ -553,7 +553,7 @@ DB.prototype.eval = function(jsfunction) {
throw _getErrorWithCode(res, tojson(res));
return res.retval;
-}
+};
DB.prototype.dbEval = DB.prototype.eval;
@@ -626,10 +626,10 @@ DB.prototype.groupeval = function(parmsObj) {
}
return map.values();
- }
+ };
return this.eval(groupFunction, this._groupFixParms( parmsObj ));
-}
+};
DB.prototype.groupcmd = function( parmsObj ){
var ret = this.runCommand( { "group" : this._groupFixParms( parmsObj ) } );
@@ -637,7 +637,7 @@ DB.prototype.groupcmd = function( parmsObj ){
throw _getErrorWithCode(ret, "group command failed: " + tojson(ret));
}
return ret.retval;
-}
+};
DB.prototype.group = DB.prototype.groupcmd;
@@ -655,22 +655,22 @@ DB.prototype._groupFixParms = function( parmsObj ){
}
return parms;
-}
+};
DB.prototype.resetError = function(){
return this.runCommand( { reseterror : 1 } );
-}
+};
DB.prototype.forceError = function(){
return this.runCommand( { forceerror : 1 } );
-}
+};
DB.prototype.getLastError = function( w , wtimeout ){
var res = this.getLastErrorObj( w , wtimeout );
if ( ! res.ok )
throw _getErrorWithCode(ret, "getlasterror failed: " + tojson(res));
return res.err;
-}
+};
DB.prototype.getLastErrorObj = function( w , wtimeout ){
var cmd = { getlasterror : 1 };
if ( w ){
@@ -683,7 +683,7 @@ DB.prototype.getLastErrorObj = function( w , wtimeout ){
if ( ! res.ok )
throw _getErrorWithCode(res, "getlasterror failed: " + tojson(res));
return res;
-}
+};
DB.prototype.getLastErrorCmd = DB.prototype.getLastErrorObj;
@@ -696,7 +696,7 @@ DB.prototype.getLastErrorCmd = DB.prototype.getLastErrorObj;
*/
DB.prototype.getPrevError = function(){
return this.runCommand( { getpreverror : 1 } );
-}
+};
DB.prototype._getCollectionInfosSystemNamespaces = function(filter) {
var all = [];
@@ -727,7 +727,7 @@ DB.prototype._getCollectionInfosSystemNamespaces = function(filter) {
// Return list of objects sorted by collection name.
return all.sort(function(coll1, coll2) { return coll1.name.localeCompare(coll2.name); });
-}
+};
DB.prototype._getCollectionInfosCommand = function(filter) {
@@ -747,7 +747,7 @@ DB.prototype._getCollectionInfosCommand = function(filter) {
}
return new DBCommandCursor(this._mongo, res).toArray().sort(compareOn("name"));
-}
+};
/**
* Returns a list that contains the names and options of this database's collections, sorted by
@@ -760,34 +760,34 @@ DB.prototype.getCollectionInfos = function(filter) {
return res;
}
return this._getCollectionInfosSystemNamespaces(filter);
-}
+};
/**
* Returns this database's list of collection names in sorted order.
*/
DB.prototype.getCollectionNames = function() {
return this.getCollectionInfos().map(function(infoObj) { return infoObj.name; });
-}
+};
DB.prototype.tojson = function(){
return this._name;
-}
+};
DB.prototype.toString = function(){
return this._name;
-}
+};
-DB.prototype.isMaster = function () { return this.runCommand("isMaster"); }
+DB.prototype.isMaster = function () { return this.runCommand("isMaster"); };
var commandUnsupported = function(res) {
return (!res.ok &&
(res.errmsg.startsWith("no such cmd") ||
res.errmsg.startsWith("no such command") ||
- res.code === 59 /* CommandNotFound */))
+ res.code === 59 /* CommandNotFound */));
};
DB.prototype.currentOp = function(arg) {
- var q = {}
+ var q = {};
if ( arg ) {
if ( typeof( arg ) == "object" )
Object.extend( q , arg );
@@ -809,7 +809,7 @@ DB.prototype.currentOp = function(arg) {
}
}
return res;
-}
+};
DB.prototype.currentOP = DB.prototype.currentOp;
DB.prototype.killOp = function(op) {
@@ -827,14 +827,14 @@ DB.prototype.killOp = function(op) {
}
}
return res;
-}
+};
DB.prototype.killOP = DB.prototype.killOp;
DB.tsToSeconds = function(x){
if ( x.t && x.i )
return x.t;
return x / 4294967296; // low 32 bits are ordinal #s within a second
-}
+};
/**
Get a replication log information summary.
@@ -933,7 +933,7 @@ DB.prototype.printReplicationInfo = function() {
print("oplog first event time: " + result.tFirst);
print("oplog last event time: " + result.tLast);
print("now: " + result.now);
-}
+};
DB.prototype.printSlaveReplicationInfo = function() {
var startOptimeDate = null;
@@ -952,7 +952,7 @@ DB.prototype.printSlaveReplicationInfo = function() {
suffix = "freshest member (no primary available at the moment)";
}
print("\t" + Math.round(ago) + " secs (" + hrs + " hrs) behind the " + suffix);
- };
+ }
function getMaster(members) {
for (i in members) {
@@ -963,10 +963,10 @@ DB.prototype.printSlaveReplicationInfo = function() {
}
return null;
- };
+ }
function g(x) {
- assert( x , "how could this be null (printSlaveReplicationInfo gx)" )
+ assert( x , "how could this be null (printSlaveReplicationInfo gx)" );
print("source: " + x.host);
if ( x.syncedTo ){
var st = new Date( DB.tsToSeconds( x.syncedTo ) * 1000 );
@@ -975,7 +975,7 @@ DB.prototype.printSlaveReplicationInfo = function() {
else {
print( "\tdoing initial sync" );
}
- };
+ }
function r(x) {
assert( x , "how could this be null (printSlaveReplicationInfo rx)" );
@@ -990,7 +990,7 @@ DB.prototype.printSlaveReplicationInfo = function() {
else {
print( "\tno replication info, yet. State: " + x.stateStr );
}
- };
+ }
var L = this.getSiblingDB("local");
@@ -1022,11 +1022,11 @@ DB.prototype.printSlaveReplicationInfo = function() {
print("local.sources is empty; is this db a --slave?");
return;
}
-}
+};
DB.prototype.serverBuildInfo = function(){
return this._adminCommand( "buildinfo" );
-}
+};
// Used to trim entries from the metrics.commands that have never been executed
getActiveCommands = function(tree) {
@@ -1053,7 +1053,7 @@ getActiveCommands = function(tree) {
}
}
return result;
-}
+};
DB.prototype.serverStatus = function( options ){
var cmd = { serverStatus : 1 };
@@ -1066,23 +1066,23 @@ DB.prototype.serverStatus = function( options ){
res.metrics.commands = getActiveCommands(res.metrics.commands);
}
return res;
-}
+};
DB.prototype.hostInfo = function(){
return this._adminCommand( "hostInfo" );
-}
+};
DB.prototype.serverCmdLineOpts = function(){
return this._adminCommand( "getCmdLineOpts" );
-}
+};
DB.prototype.version = function(){
return this.serverBuildInfo().version;
-}
+};
DB.prototype.serverBits = function(){
return this.serverBuildInfo().bits;
-}
+};
DB.prototype.listCommands = function(){
var x = this.runCommand( "listCommands" );
@@ -1100,15 +1100,15 @@ DB.prototype.listCommands = function(){
print( s );
}
-}
+};
DB.prototype.printShardingStatus = function( verbose ){
printShardingStatus( this.getSiblingDB( "config" ) , verbose );
-}
+};
DB.prototype.fsyncLock = function() {
return this.adminCommand({fsync:1, lock:true});
-}
+};
DB.prototype.fsyncUnlock = function() {
var res = this.adminCommand({fsyncUnlock: 1});
@@ -1122,7 +1122,7 @@ DB.prototype.fsyncUnlock = function() {
}
}
return res;
-}
+};
DB.autocomplete = function(obj){
var colls = obj.getCollectionNames();
@@ -1132,23 +1132,23 @@ DB.autocomplete = function(obj){
ret.push(colls[i]);
}
return ret;
-}
+};
DB.prototype.setSlaveOk = function( value ) {
if( value == undefined ) value = true;
this._slaveOk = value;
-}
+};
DB.prototype.getSlaveOk = function() {
if (this._slaveOk != undefined) return this._slaveOk;
return this._mongo.getSlaveOk();
-}
+};
DB.prototype.getQueryOptions = function() {
var options = 0;
if (this.getSlaveOk()) options |= 4;
return options;
-}
+};
/* Loads any scripts contained in system.js into the client shell.
*/
@@ -1157,14 +1157,14 @@ DB.prototype.loadServerScripts = function(){
this.system.js.find().forEach(function(u) {
global[u._id] = u.value;
});
-}
+};
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////// Security shell helpers below //////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
-var _defaultWriteConcern = { w: 'majority', wtimeout: 30 * 1000 }
+var _defaultWriteConcern = { w: 'majority', wtimeout: 30 * 1000 };
function getUserObjString(userObj) {
var pwd = userObj.pwd;
@@ -1193,7 +1193,7 @@ DB.prototype._modifyCommandToDigestPasswordIfNecessary = function(cmdObj, userna
passwordDigestor + "'");
}
delete cmdObj["passwordDigestor"];
-}
+};
DB.prototype.createUser = function(userObj, writeConcern) {
var name = userObj["user"];
@@ -1223,7 +1223,7 @@ DB.prototype.createUser = function(userObj, writeConcern) {
}
throw _getErrorWithCode(res, "couldn't add user: " + res.errmsg);
-}
+};
function _hashPassword(username, password) {
if (typeof password != 'string') {
@@ -1288,7 +1288,7 @@ DB.prototype.logout = function(){
DB.prototype.removeUser = function( username, writeConcern ) {
print("WARNING: db.removeUser has been deprecated, please use db.dropUser instead");
return this.dropUser(username, writeConcern);
-}
+};
DB.prototype.dropUser = function( username, writeConcern ){
var cmdObj = {dropUser: username,
@@ -1308,7 +1308,7 @@ DB.prototype.dropUser = function( username, writeConcern ){
}
throw _getErrorWithCode(res, res.errmsg);
-}
+};
/**
* Used for removing users in systems with V1 style user information
@@ -1328,7 +1328,7 @@ DB.prototype._removeUserV1 = function(username, writeConcern) {
} else {
return false;
}
-}
+};
DB.prototype.dropAllUsers = function(writeConcern) {
var res = this.runCommand({dropAllUsersFromDatabase:1,
@@ -1339,11 +1339,11 @@ DB.prototype.dropAllUsers = function(writeConcern) {
}
return res.n;
-}
+};
DB.prototype.__pwHash = function( nonce, username, pass ) {
return hex_md5(nonce + username + _hashPassword(username, pass));
-}
+};
DB.prototype._defaultAuthenticationMechanism = null;
@@ -1358,7 +1358,7 @@ DB.prototype._getDefaultAuthenticationMechanism = function() {
return "MONGODB-CR";
}
return "SCRAM-SHA-1";
-}
+};
DB.prototype._defaultGssapiServiceName = null;
@@ -1399,7 +1399,7 @@ DB.prototype._authOrThrow = function () {
}
return good;
-}
+};
DB.prototype.auth = function() {
@@ -1411,7 +1411,7 @@ DB.prototype.auth = function() {
return 0;
}
return 1;
-}
+};
DB.prototype.grantRolesToUser = function(username, roles, writeConcern) {
var cmdObj = {grantRolesToUser: username,
@@ -1421,7 +1421,7 @@ DB.prototype.grantRolesToUser = function(username, roles, writeConcern) {
if (!res.ok) {
throw _getErrorWithCode(res, res.errmsg);
}
-}
+};
DB.prototype.revokeRolesFromUser = function(username, roles, writeConcern) {
var cmdObj = {revokeRolesFromUser: username,
@@ -1431,7 +1431,7 @@ DB.prototype.revokeRolesFromUser = function(username, roles, writeConcern) {
if (!res.ok) {
throw _getErrorWithCode(res, res.errmsg);
}
-}
+};
DB.prototype.getUser = function(username, args) {
if (typeof username != "string") {
@@ -1449,7 +1449,7 @@ DB.prototype.getUser = function(username, args) {
return null;
}
return res.users[0];
-}
+};
DB.prototype.getUsers = function(args) {
var cmdObj = {usersInfo: 1};
@@ -1467,7 +1467,7 @@ DB.prototype.getUsers = function(args) {
}
return res.users;
-}
+};
DB.prototype.createRole = function(roleObj, writeConcern) {
var name = roleObj["role"];
@@ -1482,7 +1482,7 @@ DB.prototype.createRole = function(roleObj, writeConcern) {
throw _getErrorWithCode(res, res.errmsg);
}
printjson(roleObj);
-}
+};
DB.prototype.updateRole = function(name, updateObject, writeConcern) {
var cmdObj = {updateRole:name};
@@ -1519,7 +1519,7 @@ DB.prototype.dropAllRoles = function(writeConcern) {
}
return res.n;
-}
+};
DB.prototype.grantRolesToRole = function(rolename, roles, writeConcern) {
var cmdObj = {grantRolesToRole: rolename,
@@ -1529,7 +1529,7 @@ DB.prototype.grantRolesToRole = function(rolename, roles, writeConcern) {
if (!res.ok) {
throw _getErrorWithCode(res, res.errmsg);
}
-}
+};
DB.prototype.revokeRolesFromRole = function(rolename, roles, writeConcern) {
var cmdObj = {revokeRolesFromRole: rolename,
@@ -1539,7 +1539,7 @@ DB.prototype.revokeRolesFromRole = function(rolename, roles, writeConcern) {
if (!res.ok) {
throw _getErrorWithCode(res, res.errmsg);
}
-}
+};
DB.prototype.grantPrivilegesToRole = function(rolename, privileges, writeConcern) {
var cmdObj = {grantPrivilegesToRole: rolename,
@@ -1549,7 +1549,7 @@ DB.prototype.grantPrivilegesToRole = function(rolename, privileges, writeConcern
if (!res.ok) {
throw _getErrorWithCode(res, res.errmsg);
}
-}
+};
DB.prototype.revokePrivilegesFromRole = function(rolename, privileges, writeConcern) {
var cmdObj = {revokePrivilegesFromRole: rolename,
@@ -1559,7 +1559,7 @@ DB.prototype.revokePrivilegesFromRole = function(rolename, privileges, writeConc
if (!res.ok) {
throw _getErrorWithCode(res, res.errmsg);
}
-}
+};
DB.prototype.getRole = function(rolename, args) {
if (typeof rolename != "string") {
@@ -1576,7 +1576,7 @@ DB.prototype.getRole = function(rolename, args) {
return null;
}
return res.roles[0];
-}
+};
DB.prototype.getRoles = function(args) {
var cmdObj = {rolesInfo:1};
@@ -1587,7 +1587,7 @@ DB.prototype.getRoles = function(args) {
}
return res.roles;
-}
+};
DB.prototype.setWriteConcern = function( wc ) {
if ( wc instanceof WriteConcern ) {
@@ -1614,10 +1614,10 @@ DB.prototype.unsetWriteConcern = function() {
DB.prototype.getLogComponents = function() {
return this.getMongo().getLogComponents();
-}
+};
DB.prototype.setLogLevel = function(logLevel, component) {
return this.getMongo().setLogLevel(logLevel, component);
-}
+};
}());
diff --git a/src/mongo/shell/explain_query.js b/src/mongo/shell/explain_query.js
index 30617436e36..8db9b8b2918 100644
--- a/src/mongo/shell/explain_query.js
+++ b/src/mongo/shell/explain_query.js
@@ -49,7 +49,7 @@ var DBExplainQuery = (function() {
return function() {
dbQuery[name].apply(dbQuery, arguments);
return explainQuery;
- }
+ };
}
/**
@@ -178,21 +178,21 @@ var DBExplainQuery = (function() {
else {
return explainWithLegacyQueryOption(this);
}
- }
+ };
this.next = function() {
return this.finish();
- }
+ };
this.hasNext = function() {
return !this._finished;
- }
+ };
this.forEach = function(func) {
while (this.hasNext()) {
func(this.next());
}
- }
+ };
/**
* Returns the explain resulting from running this query as a count operation.
@@ -206,7 +206,7 @@ var DBExplainQuery = (function() {
this._applySkipLimit = true;
}
return this.finish();
- }
+ };
/**
* This gets called automatically by the shell in interactive mode. It should
@@ -215,7 +215,7 @@ var DBExplainQuery = (function() {
this.shellPrint = function() {
var result = this.finish();
return tojson(result);
- }
+ };
/**
* Display help text.
@@ -242,7 +242,7 @@ var DBExplainQuery = (function() {
print("\t.snapshot()");
print("\t.sort(sortSpec)");
return __magicNoPrint;
- }
+ };
}
diff --git a/src/mongo/shell/explainable.js b/src/mongo/shell/explainable.js
index df8603d73f0..445ade758a6 100644
--- a/src/mongo/shell/explainable.js
+++ b/src/mongo/shell/explainable.js
@@ -27,7 +27,7 @@ var Explainable = (function() {
}
return verbosity;
- }
+ };
var throwOrReturn = function(explainResult) {
if (("ok" in explainResult && !explainResult.ok) || explainResult.$err) {
@@ -35,7 +35,7 @@ var Explainable = (function() {
}
return explainResult;
- }
+ };
function constructor(collection, verbosity) {
@@ -52,16 +52,16 @@ var Explainable = (function() {
this.getCollection = function() {
return this._collection;
- }
+ };
this.getVerbosity = function() {
return this._verbosity;
- }
+ };
this.setVerbosity = function(verbosity) {
this._verbosity = parseVerbosity(verbosity);
return this;
- }
+ };
this.help = function() {
print("Explainable operations");
@@ -78,7 +78,7 @@ var Explainable = (function() {
print("\t.getVerbosity()");
print("\t.setVerbosity(verbosity)");
return __magicNoPrint;
- }
+ };
//
// Pretty representations.
@@ -103,8 +103,8 @@ var Explainable = (function() {
this.aggregate = function(pipeline, extraOpts) {
if (!(pipeline instanceof Array)) {
// support legacy varargs form. (Also handles db.foo.aggregate())
- pipeline = argumentsToArray(arguments)
- extraOpts = {}
+ pipeline = argumentsToArray(arguments);
+ extraOpts = {};
}
// Add the explain option.
@@ -112,11 +112,11 @@ var Explainable = (function() {
extraOpts.explain = true;
return this._collection.aggregate(pipeline, extraOpts);
- }
+ };
this.count = function(query) {
return this.find(query).count();
- }
+ };
/**
* .explain().find() and .find().explain() mean the same thing. In both cases, we use
@@ -126,7 +126,7 @@ var Explainable = (function() {
this.find = function() {
var cursor = this._collection.find.apply(this._collection, arguments);
return new DBExplainQuery(cursor, this._verbosity);
- }
+ };
this.findAndModify = function(params) {
var famCmd = Object.extend({"findAndModify": this._collection.getName()}, params);
@@ -141,7 +141,7 @@ var Explainable = (function() {
var explainCmd = {"explain": grpCmd, "verbosity": this._verbosity};
var explainResult = this._collection.runReadCommand(explainCmd);
return throwOrReturn(explainResult);
- }
+ };
this.distinct = function(keyString, query) {
var distinctCmd = {distinct: this._collection.getName(),
@@ -150,7 +150,7 @@ var Explainable = (function() {
var explainCmd = {explain: distinctCmd, verbosity: this._verbosity};
var explainResult = this._collection.runReadCommand(explainCmd);
return throwOrReturn(explainResult);
- }
+ };
this.remove = function() {
var parsed = this._collection._parseRemove.apply(this._collection, arguments);
@@ -169,7 +169,7 @@ var Explainable = (function() {
var explainCmd = bulk.convertToExplainCmd(this._verbosity);
var explainResult = this._collection.runCommand(explainCmd);
return throwOrReturn(explainResult);
- }
+ };
this.update = function() {
var parsed = this._collection._parseUpdate.apply(this._collection, arguments);
@@ -195,7 +195,7 @@ var Explainable = (function() {
var explainCmd = bulk.convertToExplainCmd(this._verbosity);
var explainResult = this._collection.runCommand(explainCmd);
return throwOrReturn(explainResult);
- }
+ };
}
diff --git a/src/mongo/shell/mongo.js b/src/mongo/shell/mongo.js
index 52a835a2e89..3dd44fee978 100644
--- a/src/mongo/shell/mongo.js
+++ b/src/mongo/shell/mongo.js
@@ -4,7 +4,7 @@
if ( typeof Mongo == "undefined" ){
Mongo = function( host ){
this.init( host );
- }
+ };
}
if ( ! Mongo.prototype ){
@@ -12,13 +12,13 @@ if ( ! Mongo.prototype ){
}
if ( ! Mongo.prototype.find )
- Mongo.prototype.find = function( ns , query , fields , limit , skip , batchSize , options ){ throw Error("find not implemented"); }
+ Mongo.prototype.find = function( ns , query , fields , limit , skip , batchSize , options ){ throw Error("find not implemented"); };
if ( ! Mongo.prototype.insert )
- Mongo.prototype.insert = function( ns , obj ){ throw Error("insert not implemented"); }
+ Mongo.prototype.insert = function( ns , obj ){ throw Error("insert not implemented"); };
if ( ! Mongo.prototype.remove )
- Mongo.prototype.remove = function( ns , pattern ){ throw Error("remove not implemented"); }
+ Mongo.prototype.remove = function( ns , pattern ){ throw Error("remove not implemented"); };
if ( ! Mongo.prototype.update )
- Mongo.prototype.update = function( ns , query , obj , upsert ){ throw Error("update not implemented"); }
+ Mongo.prototype.update = function( ns , query , obj , upsert ){ throw Error("update not implemented"); };
if ( typeof mongoInject == "function" ){
mongoInject( Mongo.prototype );
@@ -27,16 +27,16 @@ if ( typeof mongoInject == "function" ){
Mongo.prototype.setSlaveOk = function( value ) {
if( value == undefined ) value = true;
this.slaveOk = value;
-}
+};
Mongo.prototype.getSlaveOk = function() {
return this.slaveOk || false;
-}
+};
Mongo.prototype.getDB = function( name ){
if ((jsTest.options().keyFile) &&
((typeof this.authenticated == 'undefined') || !this.authenticated)) {
- jsTest.authenticate(this)
+ jsTest.authenticate(this);
}
// There is a weird issue where typeof(db._name) !== "string" when the db name
// is created from objects returned from native C++ methods.
@@ -45,18 +45,18 @@ Mongo.prototype.getDB = function( name ){
name = name.toString();
}
return new DB( this , name );
-}
+};
Mongo.prototype.getDBs = function(){
var res = this.getDB( "admin" ).runCommand( { "listDatabases" : 1 } );
if ( ! res.ok )
throw _getErrorWithCode(res, "listDatabases failed:" + tojson(res));
return res;
-}
+};
Mongo.prototype.adminCommand = function( cmd ){
return this.getDB( "admin" ).runCommand( cmd );
-}
+};
/**
* Returns all log components and current verbosity values
@@ -66,7 +66,7 @@ Mongo.prototype.getLogComponents = function() {
if (!res.ok)
throw _getErrorWithCode(res, "getLogComponents failed:" + tojson(res));
return res.logComponentVerbosity;
-}
+};
/**
* Accepts optional second argument "component",
@@ -93,7 +93,7 @@ Mongo.prototype.setLogLevel = function(logLevel, component) {
if (!res.ok)
throw _getErrorWithCode(res, "setLogLevel failed:" + tojson(res));
return res;
-}
+};
Mongo.prototype.getDBNames = function(){
return this.getDBs().databases.map(
@@ -101,7 +101,7 @@ Mongo.prototype.getDBNames = function(){
return z.name;
}
);
-}
+};
Mongo.prototype.getCollection = function(ns){
var idx = ns.indexOf( "." );
@@ -110,11 +110,11 @@ Mongo.prototype.getCollection = function(ns){
var db = ns.substring( 0 , idx );
var c = ns.substring( idx + 1 );
return this.getDB( db ).getCollection( c );
-}
+};
Mongo.prototype.toString = function(){
return "connection to " + this.host;
-}
+};
Mongo.prototype.tojson = Mongo.prototype.toString;
/**
@@ -212,7 +212,7 @@ connect = function(url, user, pass) {
}
}
- chatty("connecting to: " + url)
+ chatty("connecting to: " + url);
var db;
if (url.startsWith("mongodb://")) {
db = new Mongo(url);
@@ -231,30 +231,30 @@ connect = function(url, user, pass) {
}
}
return db;
-}
+};
/** deprecated, use writeMode below
*
*/
Mongo.prototype.useWriteCommands = function() {
- return (this.writeMode() != "legacy");
-}
+ return (this.writeMode() != "legacy");
+};
Mongo.prototype.forceWriteMode = function( mode ) {
this._writeMode = mode;
-}
+};
Mongo.prototype.hasWriteCommands = function() {
var hasWriteCommands = (this.getMinWireVersion() <= 2 &&
2 <= this.getMaxWireVersion());
return hasWriteCommands;
-}
+};
Mongo.prototype.hasExplainCommand = function() {
var hasExplain = (this.getMinWireVersion() <= 3 &&
3 <= this.getMaxWireVersion());
return hasExplain;
-}
+};
/**
* {String} Returns the current mode set. Will be commands/legacy/compatibility
@@ -292,7 +292,7 @@ Mongo.prototype.writeMode = function() {
*/
Mongo.prototype.useReadCommands = function() {
return (this.readMode() === "commands");
-}
+};
/**
* For testing, forces the shell to use the readMode specified in 'mode'. Must be either "commands"
diff --git a/src/mongo/shell/mr.js b/src/mongo/shell/mr.js
index 7b0814dd557..fbc7d2bbf17 100644
--- a/src/mongo/shell/mr.js
+++ b/src/mongo/shell/mr.js
@@ -10,12 +10,12 @@ MR.init = function(){
$numReduces = 0;
$numReducesToDB = 0;
gc(); // this is just so that keep memory size sane
-}
+};
MR.cleanup = function(){
MR.init();
gc();
-}
+};
MR.emit = function(k,v){
$numEmits++;
@@ -27,7 +27,7 @@ MR.emit = function(k,v){
}
data.values[data.count++] = v;
$max = Math.max( $max , data.count );
-}
+};
MR.doReduce = function( useDB ){
$numReduces++;
@@ -67,7 +67,7 @@ MR.doReduce = function( useDB ){
}
}
}
-}
+};
MR.check = function(){
if ( $max < 2000 && $arr.length < 1000 ){
@@ -83,7 +83,7 @@ MR.check = function(){
reset_num();
gc();
return 2;
-}
+};
MR.finalize = function(){
tempcoll.find().forEach(
@@ -92,4 +92,4 @@ MR.finalize = function(){
tempcoll.save( z );
}
);
-}
+};
diff --git a/src/mongo/shell/query.js b/src/mongo/shell/query.js
index 823d703a167..ac9f811a19f 100644
--- a/src/mongo/shell/query.js
+++ b/src/mongo/shell/query.js
@@ -19,47 +19,47 @@ if ( typeof DBQuery == "undefined" ){
this._numReturned = 0;
this._special = false;
this._prettyShell = false;
- }
+ };
print( "DBQuery probably won't have array access " );
}
DBQuery.prototype.help = function () {
- print("find(<predicate>, <projection>) modifiers")
- print("\t.sort({...})")
- print("\t.limit(<n>)")
- print("\t.skip(<n>)")
- print("\t.batchSize(<n>) - sets the number of docs to return per getMore")
- print("\t.hint({...})")
- print("\t.readConcern(<level>)")
- print("\t.readPref(<mode>, <tagset>)")
- print("\t.count(<applySkipLimit>) - total # of objects matching query. by default ignores skip,limit")
- print("\t.size() - total # of objects cursor would return, honors skip,limit")
- print("\t.explain(<verbosity>) - accepted verbosities are {'queryPlanner', 'executionStats', 'allPlansExecution'}")
- print("\t.min({...})")
- print("\t.max({...})")
- print("\t.maxScan(<n>)")
- print("\t.maxTimeMS(<n>)")
- print("\t.comment(<comment>)")
- print("\t.snapshot()")
- print("\t.tailable(<isAwaitData>)")
- print("\t.noCursorTimeout()")
- print("\t.allowPartialResults()")
- print("\t.returnKey()")
- print("\t.showRecordId() - adds a $recordId field to each returned object")
+ print("find(<predicate>, <projection>) modifiers");
+ print("\t.sort({...})");
+ print("\t.limit(<n>)");
+ print("\t.skip(<n>)");
+ print("\t.batchSize(<n>) - sets the number of docs to return per getMore");
+ print("\t.hint({...})");
+ print("\t.readConcern(<level>)");
+ print("\t.readPref(<mode>, <tagset>)");
+ print("\t.count(<applySkipLimit>) - total # of objects matching query. by default ignores skip,limit");
+ print("\t.size() - total # of objects cursor would return, honors skip,limit");
+ print("\t.explain(<verbosity>) - accepted verbosities are {'queryPlanner', 'executionStats', 'allPlansExecution'}");
+ print("\t.min({...})");
+ print("\t.max({...})");
+ print("\t.maxScan(<n>)");
+ print("\t.maxTimeMS(<n>)");
+ print("\t.comment(<comment>)");
+ print("\t.snapshot()");
+ print("\t.tailable(<isAwaitData>)");
+ print("\t.noCursorTimeout()");
+ print("\t.allowPartialResults()");
+ print("\t.returnKey()");
+ print("\t.showRecordId() - adds a $recordId field to each returned object");
print("\nCursor methods");
- print("\t.toArray() - iterates through docs and returns an array of the results")
- print("\t.forEach(<func>)")
- print("\t.map(<func>)")
- print("\t.hasNext()")
- print("\t.next()")
- print("\t.close()")
- print("\t.objsLeftInBatch() - returns count of docs left in current batch (when exhausted, a new getMore will be issued)")
- print("\t.itcount() - iterates through documents and counts them")
+ print("\t.toArray() - iterates through docs and returns an array of the results");
+ print("\t.forEach(<func>)");
+ print("\t.map(<func>)");
+ print("\t.hasNext()");
+ print("\t.next()");
+ print("\t.close()");
+ print("\t.objsLeftInBatch() - returns count of docs left in current batch (when exhausted, a new getMore will be issued)");
+ print("\t.itcount() - iterates through documents and counts them");
print("\t.getQueryPlan() - get query plans associated with shape. To get more info on query plans, " +
"call getQueryPlan().help().");
- print("\t.pretty() - pretty print each document, possibly over multiple lines")
-}
+ print("\t.pretty() - pretty print each document, possibly over multiple lines");
+};
DBQuery.prototype.clone = function(){
var q = new DBQuery( this._mongo , this._db , this._collection , this._ns ,
@@ -67,7 +67,7 @@ DBQuery.prototype.clone = function(){
this._limit , this._skip , this._batchSize , this._options );
q._special = this._special;
return q;
-}
+};
DBQuery.prototype._ensureSpecial = function(){
if ( this._special )
@@ -76,12 +76,12 @@ DBQuery.prototype._ensureSpecial = function(){
var n = { query : this._query };
this._query = n;
this._special = true;
-}
+};
DBQuery.prototype._checkModify = function(){
if ( this._cursor )
throw Error("query already executed");
-}
+};
DBQuery.prototype._canUseFindCommand = function() {
// Since runCommand() is implemented by running a findOne() against the $cmd collection, we have
@@ -91,7 +91,7 @@ DBQuery.prototype._canUseFindCommand = function() {
// find command does not support exhaust.
return (this._collection.getName().indexOf("$cmd") !== 0)
&& (this._options & DBQuery.Option.exhaust) === 0;
-}
+};
DBQuery.prototype._exec = function(){
if ( ! this._cursor ){
@@ -119,7 +119,7 @@ DBQuery.prototype._exec = function(){
}
}
return this._cursor;
-}
+};
/**
* Internal helper used to convert this cursor into the format required by the find command.
@@ -142,7 +142,7 @@ DBQuery.prototype._convertToCommand = function(canAttachReadPref) {
}
if (this._skip) {
- cmd["skip"] = this._skip
+ cmd["skip"] = this._skip;
}
if (this._batchSize) {
@@ -242,31 +242,31 @@ DBQuery.prototype._convertToCommand = function(canAttachReadPref) {
}
return cmd;
-}
+};
DBQuery.prototype.limit = function( limit ){
this._checkModify();
this._limit = limit;
return this;
-}
+};
DBQuery.prototype.batchSize = function( batchSize ){
this._checkModify();
this._batchSize = batchSize;
return this;
-}
+};
DBQuery.prototype.addOption = function( option ){
this._options |= option;
return this;
-}
+};
DBQuery.prototype.skip = function( skip ){
this._checkModify();
this._skip = skip;
return this;
-}
+};
DBQuery.prototype.hasNext = function(){
this._exec();
@@ -277,7 +277,7 @@ DBQuery.prototype.hasNext = function(){
}
var o = this._cursor.hasNext();
return o;
-}
+};
DBQuery.prototype.next = function(){
this._exec();
@@ -295,7 +295,7 @@ DBQuery.prototype.next = function(){
this._numReturned++;
return ret;
-}
+};
DBQuery.prototype.objsLeftInBatch = function(){
this._exec();
@@ -305,13 +305,13 @@ DBQuery.prototype.objsLeftInBatch = function(){
throw _getErrorWithCode(ret, "error: " + tojson( ret ));
return ret;
-}
+};
DBQuery.prototype.readOnly = function(){
this._exec();
this._cursor.readOnly();
return this;
-}
+};
DBQuery.prototype.toArray = function(){
if ( this._arr )
@@ -322,7 +322,7 @@ DBQuery.prototype.toArray = function(){
a.push( this.next() );
this._arr = a;
return a;
-}
+};
DBQuery.prototype._convertToCountCmd = function( applySkipLimit ) {
var cmd = { count: this._collection.getName() };
@@ -354,7 +354,7 @@ DBQuery.prototype._convertToCountCmd = function( applySkipLimit ) {
}
return cmd;
-}
+};
DBQuery.prototype.count = function( applySkipLimit ) {
var cmd = this._convertToCountCmd( applySkipLimit );
@@ -362,11 +362,11 @@ DBQuery.prototype.count = function( applySkipLimit ) {
var res = this._db.runReadCommand( cmd );
if( res && res.n != null ) return res.n;
throw _getErrorWithCode(res, "count failed: " + tojson( res ));
-}
+};
DBQuery.prototype.size = function(){
return this.count( true );
-}
+};
DBQuery.prototype.countReturn = function(){
var c = this.count();
@@ -378,7 +378,7 @@ DBQuery.prototype.countReturn = function(){
return this._limit;
return c;
-}
+};
/**
* iterative count - only for testing
@@ -405,48 +405,48 @@ DBQuery.prototype.itcount = function(){
}
}
return num;
-}
+};
DBQuery.prototype.length = function(){
return this.toArray().length;
-}
+};
DBQuery.prototype._addSpecial = function( name , value ){
this._ensureSpecial();
this._query[name] = value;
return this;
-}
+};
DBQuery.prototype.sort = function( sortBy ){
return this._addSpecial( "orderby" , sortBy );
-}
+};
DBQuery.prototype.hint = function( hint ){
return this._addSpecial( "$hint" , hint );
-}
+};
DBQuery.prototype.min = function( min ) {
return this._addSpecial( "$min" , min );
-}
+};
DBQuery.prototype.max = function( max ) {
return this._addSpecial( "$max" , max );
-}
+};
/**
* Deprecated. Use showRecordId().
*/
DBQuery.prototype.showDiskLoc = function() {
return this.showRecordId();
-}
+};
DBQuery.prototype.showRecordId = function() {
return this._addSpecial("$showDiskLoc", true);
-}
+};
DBQuery.prototype.maxTimeMS = function( maxTimeMS ) {
return this._addSpecial( "$maxTimeMS" , maxTimeMS );
-}
+};
DBQuery.prototype.readConcern = function( level ) {
var readConcernObj = {
@@ -454,7 +454,7 @@ DBQuery.prototype.readConcern = function( level ) {
};
return this._addSpecial( "readConcern", readConcernObj );
-}
+};
/**
* Sets the read preference for this cursor.
@@ -480,44 +480,44 @@ DBQuery.prototype.readPref = function( mode, tagSet ) {
DBQuery.prototype.forEach = function( func ){
while ( this.hasNext() )
func( this.next() );
-}
+};
DBQuery.prototype.map = function( func ){
var a = [];
while ( this.hasNext() )
a.push( func( this.next() ) );
return a;
-}
+};
DBQuery.prototype.arrayAccess = function( idx ){
return this.toArray()[idx];
-}
+};
DBQuery.prototype.comment = function (comment) {
return this._addSpecial( "$comment" , comment );
-}
+};
DBQuery.prototype.explain = function (verbose) {
var explainQuery = new DBExplainQuery(this, verbose);
return explainQuery.finish();
-}
+};
DBQuery.prototype.snapshot = function(){
return this._addSpecial( "$snapshot" , true );
-}
+};
DBQuery.prototype.returnKey = function(){
return this._addSpecial( "$returnKey" , true );
-}
+};
DBQuery.prototype.maxScan = function(n){
return this._addSpecial( "$maxScan" , n );
-}
+};
DBQuery.prototype.pretty = function(){
this._prettyShell = true;
return this;
-}
+};
DBQuery.prototype.shellPrint = function(){
try {
@@ -544,18 +544,18 @@ DBQuery.prototype.shellPrint = function(){
print( e );
}
-}
+};
/**
* Returns a QueryPlan for the query.
*/
DBQuery.prototype.getQueryPlan = function() {
return new QueryPlan( this );
-}
+};
DBQuery.prototype.toString = function(){
return "DBQuery: " + this._ns + " -> " + tojson( this._query );
-}
+};
//
// CRUD specification find cursor extension
@@ -572,7 +572,7 @@ DBQuery.prototype.allowPartialResults = function() {
this._checkModify();
this.addOption(DBQuery.Option.partial);
return this;
-}
+};
/**
* The server normally times out idle cursors after an inactivity period (10 minutes)
@@ -586,7 +586,7 @@ DBQuery.prototype.noCursorTimeout = function() {
this._checkModify();
this.addOption(DBQuery.Option.noTimeout);
return this;
-}
+};
/**
* Internal replication use only - driver should not set
@@ -599,7 +599,7 @@ DBQuery.prototype.oplogReplay = function() {
this._checkModify();
this.addOption(DBQuery.Option.oplogReplay);
return this;
-}
+};
/**
* Limits the fields to return for all matching documents.
@@ -613,7 +613,7 @@ DBQuery.prototype.projection = function(document) {
this._checkModify();
this._fields = document;
return this;
-}
+};
/**
* Specify cursor as a tailable cursor, allowing to specify if it will use awaitData
@@ -633,7 +633,7 @@ DBQuery.prototype.tailable = function(awaitData) {
}
return this;
-}
+};
/**
* Specify a document containing modifiers for the query.
@@ -657,11 +657,11 @@ DBQuery.prototype.modifiers = function(document) {
}
return this;
-}
+};
DBQuery.prototype.close = function() {
- this._cursor.close()
-}
+ this._cursor.close();
+};
DBQuery.shellBatchSize = 20;
@@ -723,7 +723,7 @@ DBCommandCursor.prototype.close = function() {
this._cursorHandle.zeroCursorId();
this._cursorid = NumberLong(0);
}
-}
+};
/**
* Fills out this._batch by running a getMore command. If the cursor is exhausted, also resets
@@ -764,7 +764,7 @@ DBCommandCursor.prototype._runGetMoreCommand = function() {
// Successfully retrieved the next batch.
this._batch = cmdRes.cursor.nextBatch.reverse();
-}
+};
DBCommandCursor.prototype._hasNextUsingCommands = function() {
assert(this._useReadCommands);
@@ -778,7 +778,7 @@ DBCommandCursor.prototype._hasNextUsingCommands = function() {
}
return this._batch.length > 0;
-}
+};
DBCommandCursor.prototype.hasNext = function() {
if (this._useReadCommands) {
@@ -786,7 +786,7 @@ DBCommandCursor.prototype.hasNext = function() {
}
return this._batch.length || this._cursor.hasNext();
-}
+};
DBCommandCursor.prototype.next = function() {
if (this._batch.length) {
@@ -807,7 +807,7 @@ DBCommandCursor.prototype.next = function() {
throw _getErrorWithCode(ret, "error: " + tojson(ret));
return ret;
}
-}
+};
DBCommandCursor.prototype.objsLeftInBatch = function() {
if (this._useReadCommands) {
return this._batch.length;
@@ -818,29 +818,29 @@ DBCommandCursor.prototype.objsLeftInBatch = function() {
else {
return this._cursor.objsLeftInBatch();
}
-}
+};
DBCommandCursor.prototype.help = function () {
// This is the same as the "Cursor Methods" section of DBQuery.help().
print("\nCursor methods");
- print("\t.toArray() - iterates through docs and returns an array of the results")
- print("\t.forEach( func )")
- print("\t.map( func )")
- print("\t.hasNext()")
- print("\t.next()")
- print("\t.objsLeftInBatch() - returns count of docs left in current batch (when exhausted, a new getMore will be issued)")
- print("\t.itcount() - iterates through documents and counts them")
- print("\t.pretty() - pretty print each document, possibly over multiple lines")
- print("\t.close()")
-}
+ print("\t.toArray() - iterates through docs and returns an array of the results");
+ print("\t.forEach( func )");
+ print("\t.map( func )");
+ print("\t.hasNext()");
+ print("\t.next()");
+ print("\t.objsLeftInBatch() - returns count of docs left in current batch (when exhausted, a new getMore will be issued)");
+ print("\t.itcount() - iterates through documents and counts them");
+ print("\t.pretty() - pretty print each document, possibly over multiple lines");
+ print("\t.close()");
+};
// Copy these methods from DBQuery
-DBCommandCursor.prototype.toArray = DBQuery.prototype.toArray
-DBCommandCursor.prototype.forEach = DBQuery.prototype.forEach
-DBCommandCursor.prototype.map = DBQuery.prototype.map
-DBCommandCursor.prototype.itcount = DBQuery.prototype.itcount
-DBCommandCursor.prototype.shellPrint = DBQuery.prototype.shellPrint
-DBCommandCursor.prototype.pretty = DBQuery.prototype.pretty
+DBCommandCursor.prototype.toArray = DBQuery.prototype.toArray;
+DBCommandCursor.prototype.forEach = DBQuery.prototype.forEach;
+DBCommandCursor.prototype.map = DBQuery.prototype.map;
+DBCommandCursor.prototype.itcount = DBQuery.prototype.itcount;
+DBCommandCursor.prototype.shellPrint = DBQuery.prototype.shellPrint;
+DBCommandCursor.prototype.pretty = DBQuery.prototype.pretty;
/**
* QueryCache
@@ -850,7 +850,7 @@ DBCommandCursor.prototype.pretty = DBQuery.prototype.pretty
if ( ( typeof QueryPlan ) == "undefined" ){
QueryPlan = function( cursor ){
this._cursor = cursor;
- }
+ };
}
/**
@@ -859,7 +859,7 @@ if ( ( typeof QueryPlan ) == "undefined" ){
*/
QueryPlan.prototype.getName = function() {
return this._cursor._collection.getName();
-}
+};
/**
* tojson prints the name of the collection
@@ -867,7 +867,7 @@ QueryPlan.prototype.getName = function() {
QueryPlan.prototype.tojson = function(indent, nolint) {
return tojson(this.getPlans());
-}
+};
/**
* Displays help for a PlanCache object.
@@ -879,14 +879,14 @@ QueryPlan.prototype.help = function () {
print("\t.clearPlans() - drops query shape from plan cache");
print("\t.getPlans() - displays the cached plans for a query shape");
return __magicNoPrint;
-}
+};
/**
* List plans for a query shape.
*/
QueryPlan.prototype.getPlans = function() {
return this._cursor._collection.getPlanCache().getPlansByQuery(this._cursor);
-}
+};
/**
* Drop query shape from the plan cache.
@@ -894,4 +894,4 @@ QueryPlan.prototype.getPlans = function() {
QueryPlan.prototype.clearPlans = function() {
this._cursor._collection.getPlanCache().clearPlansByQuery(this._cursor);
return;
-}
+};
diff --git a/src/mongo/shell/servers.js b/src/mongo/shell/servers.js
index fdca7e4749a..78653c04627 100755
--- a/src/mongo/shell/servers.js
+++ b/src/mongo/shell/servers.js
@@ -11,7 +11,7 @@ _parsePath = function() {
throw Error("No dbpath specified");
return dbpath;
-}
+};
_parsePort = function() {
var port = "";
@@ -22,7 +22,7 @@ _parsePort = function() {
if ( port == "" )
throw Error("No port specified");
return port;
-}
+};
connectionURLTheSame = function( a , b ){
@@ -32,37 +32,37 @@ connectionURLTheSame = function( a , b ){
if ( ! a || ! b )
return false;
- if( a.host ) return connectionURLTheSame( a.host, b )
- if( b.host ) return connectionURLTheSame( a, b.host )
+ if( a.host ) return connectionURLTheSame( a.host, b );
+ if( b.host ) return connectionURLTheSame( a, b.host );
- if( a.name ) return connectionURLTheSame( a.name, b )
- if( b.name ) return connectionURLTheSame( a, b.name )
+ if( a.name ) return connectionURLTheSame( a.name, b );
+ if( b.name ) return connectionURLTheSame( a, b.name );
if( a.indexOf( "/" ) < 0 && b.indexOf( "/" ) < 0 ){
- a = a.split( ":" )
- b = b.split( ":" )
+ a = a.split( ":" );
+ b = b.split( ":" );
- if( a.length != b.length ) return false
+ if( a.length != b.length ) return false;
- if( a.length == 2 && a[1] != b[1] ) return false
+ if( a.length == 2 && a[1] != b[1] ) return false;
- if( a[0] == "localhost" || a[0] == "127.0.0.1" ) a[0] = getHostName()
- if( b[0] == "localhost" || b[0] == "127.0.0.1" ) b[0] = getHostName()
+ if( a[0] == "localhost" || a[0] == "127.0.0.1" ) a[0] = getHostName();
+ if( b[0] == "localhost" || b[0] == "127.0.0.1" ) b[0] = getHostName();
- return a[0] == b[0]
+ return a[0] == b[0];
}
else {
- var a0 = a.split( "/" )[0]
- var b0 = b.split( "/" )[0]
- return a0 == b0
+ var a0 = a.split( "/" )[0];
+ var b0 = b.split( "/" )[0];
+ return a0 == b0;
}
-}
+};
-assert( connectionURLTheSame( "foo" , "foo" ) )
-assert( ! connectionURLTheSame( "foo" , "bar" ) )
+assert( connectionURLTheSame( "foo" , "foo" ) );
+assert( ! connectionURLTheSame( "foo" , "bar" ) );
-assert( connectionURLTheSame( "foo/a,b" , "foo/b,a" ) )
-assert( ! connectionURLTheSame( "foo/a,b" , "bar/a,b" ) )
+assert( connectionURLTheSame( "foo/a,b" , "foo/b,a" ) );
+assert( ! connectionURLTheSame( "foo/a,b" , "bar/a,b" ) );
createMongoArgs = function( binaryName , args ){
var fullArgs = [ binaryName ];
@@ -90,22 +90,22 @@ createMongoArgs = function( binaryName , args ){
}
else {
for ( var i=0; i<args.length; i++ )
- fullArgs.push( args[i] )
+ fullArgs.push( args[i] );
}
return fullArgs;
-}
+};
-MongoRunner = function(){}
+MongoRunner = function(){};
-MongoRunner.dataDir = "/data/db"
-MongoRunner.dataPath = "/data/db/"
+MongoRunner.dataDir = "/data/db";
+MongoRunner.dataPath = "/data/db/";
MongoRunner.VersionSub = function(regex, version) {
this.regex = regex;
this.version = version;
-}
+};
// These patterns allow substituting the binary versions used for each version string to support the
// dev/stable MongoDB release cycle.
@@ -153,7 +153,7 @@ MongoRunner.areBinVersionsTheSame = function(versionA, versionB) {
return versionA.startsWith(versionB) ||
versionB.startsWith(versionA);
-}
+};
MongoRunner.logicalOptions = { runId : true,
pathOpts : true,
@@ -176,16 +176,16 @@ MongoRunner.logicalOptions = { runId : true,
noJournal : true,
binVersion : true,
waitForConnect : true,
- bridgeOptions : true }
+ bridgeOptions : true };
MongoRunner.toRealPath = function( path, pathOpts ){
// Replace all $pathOptions with actual values
- pathOpts = pathOpts || {}
- path = path.replace( /\$dataPath/g, MongoRunner.dataPath )
- path = path.replace( /\$dataDir/g, MongoRunner.dataDir )
+ pathOpts = pathOpts || {};
+ path = path.replace( /\$dataPath/g, MongoRunner.dataPath );
+ path = path.replace( /\$dataDir/g, MongoRunner.dataDir );
for( var key in pathOpts ){
- path = path.replace( RegExp( "\\$" + RegExp.escape(key), "g" ), pathOpts[ key ] )
+ path = path.replace( RegExp( "\\$" + RegExp.escape(key), "g" ), pathOpts[ key ] );
}
// Relative path
@@ -195,26 +195,26 @@ MongoRunner.toRealPath = function( path, pathOpts ){
if( ! path.match( /^(\/|\\|[A-Za-z]:)/ ) ){
if( path != "" && ! path.endsWith( "/" ) )
- path += "/"
+ path += "/";
- path = MongoRunner.dataPath + path
+ path = MongoRunner.dataPath + path;
}
- return path
+ return path;
-}
+};
MongoRunner.toRealDir = function( path, pathOpts ){
- path = MongoRunner.toRealPath( path, pathOpts )
+ path = MongoRunner.toRealPath( path, pathOpts );
if( path.endsWith( "/" ) )
- path = path.substring( 0, path.length - 1 )
+ path = path.substring( 0, path.length - 1 );
- return path
-}
+ return path;
+};
-MongoRunner.toRealFile = MongoRunner.toRealDir
+MongoRunner.toRealFile = MongoRunner.toRealDir;
/**
* Returns an iterator object which yields successive versions on toString(), starting from a
@@ -228,8 +228,8 @@ MongoRunner.toRealFile = MongoRunner.toRealDir
MongoRunner.versionIterator = function( arr, isRandom ){
// If this isn't an array of versions, or is already an iterator, just use it
- if( typeof arr == "string" ) return arr
- if( arr.isVersionIterator ) return arr
+ if( typeof arr == "string" ) return arr;
+ if( arr.isVersionIterator ) return arr;
if (isRandom == undefined) isRandom = false;
@@ -237,20 +237,20 @@ MongoRunner.versionIterator = function( arr, isRandom ){
var i = isRandom ? parseInt( Random.rand() * arr.length ) : 0;
return new MongoRunner.versionIterator.iterator(i, arr);
-}
+};
MongoRunner.versionIterator.iterator = function(i, arr) {
this.toString = function() {
- i = ( i + 1 ) % arr.length
+ i = ( i + 1 ) % arr.length;
print( "Returning next version : " + i +
" (" + arr[i] + ") from " + tojson( arr ) + "..." );
- return arr[ i ]
- }
+ return arr[ i ];
+ };
this.isVersionIterator = true;
-}
+};
/**
* Converts the args object by pairing all keys with their value and appending
@@ -265,13 +265,13 @@ MongoRunner.versionIterator.iterator = function(i, arr) {
*/
MongoRunner.arrOptions = function( binaryName , args ){
- var fullArgs = [ "" ]
+ var fullArgs = [ "" ];
// isObject returns true even if "args" is an array, so the else branch of this statement is
// dead code. See SERVER-14220.
if ( isObject( args ) || ( args.length == 1 && isObject( args[0] ) ) ){
- var o = isObject( args ) ? args : args[0]
+ var o = isObject( args ) ? args : args[0];
// If we've specified a particular binary version, use that
if (o.binVersion && o.binVersion != "") {
@@ -281,75 +281,75 @@ MongoRunner.arrOptions = function( binaryName , args ){
// Manage legacy options
var isValidOptionForBinary = function( option, value ){
- if( ! o.binVersion ) return true
+ if( ! o.binVersion ) return true;
// Version 1.x options
if( o.binVersion.startsWith( "1." ) ){
- return [ "nopreallocj" ].indexOf( option ) < 0
+ return [ "nopreallocj" ].indexOf( option ) < 0;
}
- return true
- }
+ return true;
+ };
for ( var k in o ){
// Make sure our logical option should be added to the array of options
if( ! o.hasOwnProperty( k ) ||
k in MongoRunner.logicalOptions ||
- ! isValidOptionForBinary( k, o[k] ) ) continue
+ ! isValidOptionForBinary( k, o[k] ) ) continue;
if ( ( k == "v" || k == "verbose" ) && isNumber( o[k] ) ){
- var n = o[k]
+ var n = o[k];
if ( n > 0 ){
- if ( n > 10 ) n = 10
- var temp = "-"
- while ( n-- > 0 ) temp += "v"
- fullArgs.push( temp )
+ if ( n > 10 ) n = 10;
+ var temp = "-";
+ while ( n-- > 0 ) temp += "v";
+ fullArgs.push( temp );
}
}
else {
- if( o[k] == undefined || o[k] == null ) continue
- fullArgs.push( "--" + k )
+ if( o[k] == undefined || o[k] == null ) continue;
+ fullArgs.push( "--" + k );
if ( o[k] != "" )
- fullArgs.push( "" + o[k] )
+ fullArgs.push( "" + o[k] );
}
}
}
else {
for ( var i=0; i<args.length; i++ )
- fullArgs.push( args[i] )
+ fullArgs.push( args[i] );
}
- fullArgs[ 0 ] = binaryName
- return fullArgs
-}
+ fullArgs[ 0 ] = binaryName;
+ return fullArgs;
+};
MongoRunner.arrToOpts = function( arr ){
- var opts = {}
+ var opts = {};
for( var i = 1; i < arr.length; i++ ){
if( arr[i].startsWith( "-" ) ){
- var opt = arr[i].replace( /^-/, "" ).replace( /^-/, "" )
+ var opt = arr[i].replace( /^-/, "" ).replace( /^-/, "" );
if( arr.length > i + 1 && ! arr[ i + 1 ].startsWith( "-" ) ){
- opts[ opt ] = arr[ i + 1 ]
- i++
+ opts[ opt ] = arr[ i + 1 ];
+ i++;
}
else{
- opts[ opt ] = ""
+ opts[ opt ] = "";
}
if( opt.replace( /v/g, "" ) == "" ){
- opts[ "verbose" ] = opt.length
+ opts[ "verbose" ] = opt.length;
}
}
}
- return opts
-}
+ return opts;
+};
-MongoRunner.savedOptions = {}
+MongoRunner.savedOptions = {};
MongoRunner.mongoOptions = function(opts) {
// Don't remember waitForConnect
@@ -358,44 +358,44 @@ MongoRunner.mongoOptions = function(opts) {
// If we're a mongo object
if( opts.getDB ){
- opts = { restart : opts.runId }
+ opts = { restart : opts.runId };
}
// Initialize and create a copy of the opts
- opts = Object.merge( opts || {}, {} )
+ opts = Object.merge( opts || {}, {} );
- if( ! opts.restart ) opts.restart = false
+ if( ! opts.restart ) opts.restart = false;
// RunId can come from a number of places
// If restart is passed as an old connection
if( opts.restart && opts.restart.getDB ){
- opts.runId = opts.restart.runId
- opts.restart = true
+ opts.runId = opts.restart.runId;
+ opts.restart = true;
}
// If it's the runId itself
else if( isObject( opts.restart ) ){
- opts.runId = opts.restart
- opts.restart = true
+ opts.runId = opts.restart;
+ opts.restart = true;
}
if( isObject( opts.remember ) ){
- opts.runId = opts.remember
- opts.remember = true
+ opts.runId = opts.remember;
+ opts.remember = true;
}
else if( opts.remember == undefined ){
// Remember by default if we're restarting
- opts.remember = opts.restart
+ opts.remember = opts.restart;
}
// If we passed in restart : <conn> or runId : <conn>
- if( isObject( opts.runId ) && opts.runId.runId ) opts.runId = opts.runId.runId
+ if( isObject( opts.runId ) && opts.runId.runId ) opts.runId = opts.runId.runId;
if (opts.restart && opts.remember) {
opts = Object.merge(MongoRunner.savedOptions[ opts.runId ], opts);
}
// Create a new runId
- opts.runId = opts.runId || ObjectId()
+ opts.runId = opts.runId || ObjectId();
if (opts.forgetPort) {
delete opts.port;
@@ -421,8 +421,8 @@ MongoRunner.mongoOptions = function(opts) {
MongoRunner.savedOptions[opts.runId] = Object.merge(opts, {});
}
- return opts
-}
+ return opts;
+};
/**
* @option {object} opts
@@ -441,18 +441,18 @@ MongoRunner.mongoOptions = function(opts) {
*/
MongoRunner.mongodOptions = function( opts ){
- opts = MongoRunner.mongoOptions( opts )
+ opts = MongoRunner.mongoOptions( opts );
opts.dbpath = MongoRunner.toRealDir( opts.dbpath || "$dataDir/mongod-$port",
- opts.pathOpts )
+ opts.pathOpts );
- opts.pathOpts = Object.merge( opts.pathOpts, { dbpath : opts.dbpath } )
+ opts.pathOpts = Object.merge( opts.pathOpts, { dbpath : opts.dbpath } );
if( ! opts.logFile && opts.useLogFiles ){
- opts.logFile = opts.dbpath + "/mongod.log"
+ opts.logFile = opts.dbpath + "/mongod.log";
}
else if( opts.logFile ){
- opts.logFile = MongoRunner.toRealFile( opts.logFile, opts.pathOpts )
+ opts.logFile = MongoRunner.toRealFile( opts.logFile, opts.pathOpts );
}
if ( opts.logFile !== undefined ) {
@@ -460,16 +460,16 @@ MongoRunner.mongodOptions = function( opts ){
}
if( jsTestOptions().noJournalPrealloc || opts.noJournalPrealloc )
- opts.nopreallocj = ""
+ opts.nopreallocj = "";
if((jsTestOptions().noJournal || opts.noJournal) &&
!('journal' in opts) &&
!('configsvr' in opts)) {
- opts.nojournal = ""
+ opts.nojournal = "";
}
if( jsTestOptions().keyFile && !opts.keyFile) {
- opts.keyFile = jsTestOptions().keyFile
+ opts.keyFile = jsTestOptions().keyFile;
}
if (opts.hasOwnProperty("enableEncryption")) {
@@ -524,29 +524,29 @@ MongoRunner.mongodOptions = function( opts ){
opts.enableMajorityReadConcern = "";
}
- if( opts.noReplSet ) opts.replSet = null
- if( opts.arbiter ) opts.oplogSize = 1
+ if( opts.noReplSet ) opts.replSet = null;
+ if( opts.arbiter ) opts.oplogSize = 1;
- return opts
-}
+ return opts;
+};
MongoRunner.mongosOptions = function( opts ) {
opts = MongoRunner.mongoOptions(opts);
// Normalize configdb option to be host string if currently a host
if( opts.configdb && opts.configdb.getDB ){
- opts.configdb = opts.configdb.host
+ opts.configdb = opts.configdb.host;
}
opts.pathOpts = Object.merge( opts.pathOpts,
- { configdb : opts.configdb.replace( /:|\/|,/g, "-" ) } )
+ { configdb : opts.configdb.replace( /:|\/|,/g, "-" ) } );
if( ! opts.logFile && opts.useLogFiles ){
opts.logFile = MongoRunner.toRealFile( "$dataDir/mongos-$configdb-$port.log",
- opts.pathOpts )
+ opts.pathOpts );
}
else if( opts.logFile ){
- opts.logFile = MongoRunner.toRealFile( opts.logFile, opts.pathOpts )
+ opts.logFile = MongoRunner.toRealFile( opts.logFile, opts.pathOpts );
}
if ( opts.logFile !== undefined ){
@@ -574,8 +574,8 @@ MongoRunner.mongosOptions = function( opts ) {
opts.binVersion = MongoRunner.getBinVersionFor(testOptions.mongosBinVersion);
}
- return opts
-}
+ return opts;
+};
/**
* Starts a mongod instance.
@@ -600,7 +600,7 @@ MongoRunner.mongosOptions = function( opts ) {
*/
MongoRunner.runMongod = function( opts ){
- opts = opts || {}
+ opts = opts || {};
var useHostName = true;
var runId = null;
var waitForConnect = true;
@@ -623,33 +623,33 @@ MongoRunner.runMongod = function( opts ){
runId = opts.runId;
waitForConnect = opts.waitForConnect;
- if( opts.forceLock ) removeFile( opts.dbpath + "/mongod.lock" )
+ if( opts.forceLock ) removeFile( opts.dbpath + "/mongod.lock" );
if( ( opts.cleanData || opts.startClean ) || ( ! opts.restart && ! opts.noCleanData ) ){
- print( "Resetting db path '" + opts.dbpath + "'" )
- resetDbpath( opts.dbpath )
+ print( "Resetting db path '" + opts.dbpath + "'" );
+ resetDbpath( opts.dbpath );
}
- opts = MongoRunner.arrOptions( "mongod", opts )
+ opts = MongoRunner.arrOptions( "mongod", opts );
}
var mongod = MongoRunner.startWithArgs(opts, waitForConnect);
if (!waitForConnect) mongod = {};
if (!mongod) return null;
- mongod.commandLine = MongoRunner.arrToOpts( opts )
- mongod.name = (useHostName ? getHostName() : "localhost") + ":" + mongod.commandLine.port
- mongod.host = mongod.name
- mongod.port = parseInt( mongod.commandLine.port )
- mongod.runId = runId || ObjectId()
+ mongod.commandLine = MongoRunner.arrToOpts( opts );
+ mongod.name = (useHostName ? getHostName() : "localhost") + ":" + mongod.commandLine.port;
+ mongod.host = mongod.name;
+ mongod.port = parseInt( mongod.commandLine.port );
+ mongod.runId = runId || ObjectId();
mongod.dbpath = fullOptions.dbpath;
mongod.savedOptions = MongoRunner.savedOptions[ mongod.runId ];
mongod.fullOptions = fullOptions;
- return mongod
-}
+ return mongod;
+};
MongoRunner.runMongos = function(opts) {
- opts = opts || {}
+ opts = opts || {};
var useHostName = false;
var runId = null;
@@ -671,21 +671,21 @@ MongoRunner.runMongos = function(opts) {
if (!waitForConnect) mongos = {};
if (!mongos) return null;
- mongos.commandLine = MongoRunner.arrToOpts( opts )
- mongos.name = (useHostName ? getHostName() : "localhost") + ":" + mongos.commandLine.port
- mongos.host = mongos.name
- mongos.port = parseInt( mongos.commandLine.port )
- mongos.runId = runId || ObjectId()
- mongos.savedOptions = MongoRunner.savedOptions[ mongos.runId ]
+ mongos.commandLine = MongoRunner.arrToOpts( opts );
+ mongos.name = (useHostName ? getHostName() : "localhost") + ":" + mongos.commandLine.port;
+ mongos.host = mongos.name;
+ mongos.port = parseInt( mongos.commandLine.port );
+ mongos.runId = runId || ObjectId();
+ mongos.savedOptions = MongoRunner.savedOptions[ mongos.runId ];
mongos.fullOptions = fullOptions;
- return mongos
-}
+ return mongos;
+};
MongoRunner.StopError = function(message, returnCode) {
this.name = "StopError";
- this.returnCode = returnCode || "non-zero"
+ this.returnCode = returnCode || "non-zero";
this.message = message || "MongoDB process stopped with exit code: " + this.returnCode;
this.stack = this.toString() + "\n" + (new Error()).stack;
};
@@ -732,8 +732,8 @@ MongoRunner.EXIT_TEST = 101;
MongoRunner.stopMongod = function( port, signal, opts ){
if( ! port ) {
- print( "Cannot stop mongo process " + port )
- return
+ print( "Cannot stop mongo process " + port );
+ return;
}
signal = parseInt(signal) || 15;
@@ -757,11 +757,11 @@ MongoRunner.stopMongod = function( port, signal, opts ){
}
if( port.port )
- port = parseInt( port.port )
+ port = parseInt( port.port );
if( port instanceof ObjectId ){
- var opts = MongoRunner.savedOptions( port )
- if( opts ) port = parseInt( opts.port )
+ var opts = MongoRunner.savedOptions( port );
+ if( opts ) port = parseInt( opts.port );
}
var returnCode = _stopMongoProgram(parseInt(port), signal, opts);
@@ -774,7 +774,7 @@ MongoRunner.stopMongod = function( port, signal, opts ){
}
return returnCode;
-}
+};
MongoRunner.stopMongos = MongoRunner.stopMongod;
@@ -791,15 +791,15 @@ MongoRunner.stopMongos = MongoRunner.stopMongod;
*/
MongoRunner.runMongoTool = function( binaryName, opts ){
- var opts = opts || {}
+ var opts = opts || {};
// Normalize and get the binary version to use
opts.binVersion = MongoRunner.getBinVersionFor(opts.binVersion);
- var argsArray = MongoRunner.arrOptions(binaryName, opts)
+ var argsArray = MongoRunner.arrOptions(binaryName, opts);
return runMongoProgram.apply(null, argsArray);
-}
+};
// Given a test name figures out a directory for that test to use for dump files and makes sure
// that directory exists and is empty.
@@ -807,7 +807,7 @@ MongoRunner.getAndPrepareDumpDirectory = function(testName) {
var dir = MongoRunner.dataPath + testName + "_external/";
resetDbpath(dir);
return dir;
-}
+};
// Start a mongod instance and return a 'Mongo' object connected to it.
// This function's arguments are passed as command line arguments to mongod.
@@ -820,17 +820,17 @@ _startMongodEmpty = function () {
resetDbpath(dbpath);
return startMongoProgram.apply(null, args);
-}
+};
_startMongod = function () {
print("startMongod WARNING DELETES DATA DIRECTORY THIS IS FOR TESTING ONLY");
return _startMongodEmpty.apply(null, arguments);
-}
+};
_startMongodNoReset = function(){
var args = createMongoArgs( "mongod" , arguments );
return startMongoProgram.apply( null, args );
-}
+};
/**
* Returns a new argArray with any test-specific arguments added.
@@ -868,7 +868,7 @@ function appendSetParameterArgs(argArray) {
var params = jsTest.options().setParametersMongos.split(",");
if (params && params.length > 0) {
params.forEach(function(p) {
- if (p) argArray.push.apply(argArray, ['--setParameter', p])
+ if (p) argArray.push.apply(argArray, ['--setParameter', p]);
});
}
}
@@ -895,14 +895,14 @@ function appendSetParameterArgs(argArray) {
var params = jsTest.options().setParameters.split(",");
if (params && params.length > 0) {
params.forEach(function(p) {
- if (p) argArray.push.apply(argArray, ['--setParameter', p])
+ if (p) argArray.push.apply(argArray, ['--setParameter', p]);
});
}
}
}
}
return argArray;
-};
+}
/**
* Start a mongo process with a particular argument array. If we aren't waiting for connect,
@@ -924,7 +924,7 @@ MongoRunner.startWithArgs = function(argArray, waitForConnect) {
} catch( e ) {
if (!checkProgram(pid)) {
- print("Could not start mongo program at " + port + ", process ended")
+ print("Could not start mongo program at " + port + ", process ended");
// Break out
return true;
@@ -935,7 +935,7 @@ MongoRunner.startWithArgs = function(argArray, waitForConnect) {
}
return conn;
-}
+};
/**
* DEPRECATED
@@ -964,7 +964,7 @@ startMongoProgram = function(){
} catch( e ) {
if (!checkProgram(pid)) {
- print("Could not start mongo program at " + port + ", process ended")
+ print("Could not start mongo program at " + port + ", process ended");
// Break out
m = null;
@@ -975,7 +975,7 @@ startMongoProgram = function(){
}, "unable to connect to mongo program on port " + port, 600 * 1000 );
return m;
-}
+};
runMongoProgram = function() {
var args = argumentsToArray( arguments );
@@ -998,7 +998,7 @@ runMongoProgram = function() {
}
return _runMongoProgram.apply( null, args );
-}
+};
// Start a mongo program instance. This function's first argument is the
// program name, and subsequent arguments to this function are passed as
@@ -1022,7 +1022,7 @@ startMongoProgramNoConnect = function() {
}
return _startMongoProgram.apply( null, args );
-}
+};
myPort = function() {
var m = db.getMongo();
@@ -1030,6 +1030,6 @@ myPort = function() {
return m.host.match( /:(.*)/ )[ 1 ];
else
return 27017;
-}
+};
}());
diff --git a/src/mongo/shell/servers_misc.js b/src/mongo/shell/servers_misc.js
index 7bf0ea1a422..1739edae0e4 100644
--- a/src/mongo/shell/servers_misc.js
+++ b/src/mongo/shell/servers_misc.js
@@ -9,7 +9,7 @@ ToolTest = function( name, extraOptions ){
this.extFile = this.root + "_external/a";
resetDbpath( this.dbpath );
resetDbpath( this.ext );
-}
+};
ToolTest.prototype.startDB = function( coll ){
assert( ! this.m , "db already running" );
@@ -28,7 +28,7 @@ ToolTest.prototype.startDB = function( coll ){
if ( coll )
return this.db.getCollection( coll );
return this.db;
-}
+};
ToolTest.prototype.stop = function(){
if ( ! this.m )
@@ -38,7 +38,7 @@ ToolTest.prototype.stop = function(){
this.db = null;
print('*** ' + this.name + " completed successfully ***");
-}
+};
ToolTest.prototype.runTool = function(){
var a = [ "mongo" + arguments[0] ];
@@ -57,28 +57,28 @@ ToolTest.prototype.runTool = function(){
}
return runMongoProgram.apply( null , a );
-}
+};
ReplTest = function( name, ports ){
this.name = name;
this.ports = ports || allocatePorts(2);
-}
+};
ReplTest.prototype.getPort = function( master ){
if ( master )
return this.ports[ 0 ];
- return this.ports[ 1 ]
-}
+ return this.ports[ 1 ];
+};
ReplTest.prototype.getPath = function( master ){
var p = MongoRunner.dataPath + this.name + "-";
if ( master )
p += "master";
else
- p += "slave"
+ p += "slave";
return p;
-}
+};
ReplTest.prototype.getOptions = function( master , extra , putBinaryFirst, norepl ){
@@ -88,9 +88,9 @@ ReplTest.prototype.getOptions = function( master , extra , putBinaryFirst, norep
if ( ! extra.oplogSize )
extra.oplogSize = "40";
- var a = []
+ var a = [];
if ( putBinaryFirst )
- a.push( "mongod" )
+ a.push( "mongod" );
a.push( "--nohttpinterface", "--noprealloc", "--bind_ip" , "127.0.0.1" , "--smallfiles" );
a.push( "--port" );
@@ -99,11 +99,11 @@ ReplTest.prototype.getOptions = function( master , extra , putBinaryFirst, norep
a.push( "--dbpath" );
a.push( this.getPath( master ) );
- if( jsTestOptions().noJournal && !('journal' in extra)) a.push( "--nojournal" )
- if( jsTestOptions().noJournalPrealloc ) a.push( "--nopreallocj" )
+ if( jsTestOptions().noJournal && !('journal' in extra)) a.push( "--nojournal" );
+ if( jsTestOptions().noJournalPrealloc ) a.push( "--nopreallocj" );
if( jsTestOptions().keyFile ) {
- a.push( "--keyFile" )
- a.push( jsTestOptions().keyFile )
+ a.push( "--keyFile" );
+ a.push( jsTestOptions().keyFile );
}
if ( !norepl ) {
@@ -119,14 +119,14 @@ ReplTest.prototype.getOptions = function( master , extra , putBinaryFirst, norep
for ( var k in extra ){
var v = extra[k];
- if( k in MongoRunner.logicalOptions ) continue
+ if( k in MongoRunner.logicalOptions ) continue;
a.push( "--" + k );
if ( v != null && v !== "")
a.push( v );
}
return a;
-}
+};
ReplTest.prototype.start = function( master , options , restart, norepl ){
var lockFile = this.getPath( master ) + "/mongod.lock";
@@ -149,7 +149,7 @@ ReplTest.prototype.start = function( master , options , restart, norepl ){
}
return conn;
}
-}
+};
ReplTest.prototype.stop = function( master , signal ){
if ( arguments.length == 0 ){
@@ -160,7 +160,7 @@ ReplTest.prototype.stop = function( master , signal ){
print('*** ' + this.name + " completed successfully ***");
return _stopMongoProgram( this.getPort( master ) , signal || 15 );
-}
+};
/**
* Returns a port number that has not been given out to any other caller from the same mongo shell.
@@ -208,7 +208,7 @@ SyncCCTest = function( testName , extraMongodOptions ){
this.url = this._connections.map( function(z){ return z.name; } ).join( "," );
this.conn = new Mongo( this.url );
-}
+};
SyncCCTest.prototype.stop = function(){
for ( var i=0; i<this._connections.length; i++){
@@ -216,7 +216,7 @@ SyncCCTest.prototype.stop = function(){
}
print('*** ' + this._testName + " completed successfully ***");
-}
+};
SyncCCTest.prototype.checkHashes = function( dbname , msg ){
var hashes = this._connections.map(
@@ -226,21 +226,21 @@ SyncCCTest.prototype.checkHashes = function( dbname , msg ){
);
for ( var i=1; i<hashes.length; i++ ){
- assert.eq( hashes[0].md5 , hashes[i].md5 , "checkHash on " + dbname + " " + msg + "\n" + tojson( hashes ) )
+ assert.eq( hashes[0].md5 , hashes[i].md5 , "checkHash on " + dbname + " " + msg + "\n" + tojson( hashes ) );
}
-}
+};
SyncCCTest.prototype.tempKill = function( num ){
num = num || 0;
MongoRunner.stopMongod(this._connections[num]);
-}
+};
SyncCCTest.prototype.tempStart = function( num ){
num = num || 0;
var old = this._connections[num];
this._connections[num] = MongoRunner.runMongod({
restart: true, cleanData: false, port: old.port, dbpath: old.dbpath});
-}
+};
function startParallelShell( jsCode, port, noConnect ){
diff --git a/src/mongo/shell/types.js b/src/mongo/shell/types.js
index e466a96b7ea..2daaddbc510 100644
--- a/src/mongo/shell/types.js
+++ b/src/mongo/shell/types.js
@@ -2,19 +2,19 @@
if (typeof(Timestamp) != "undefined"){
Timestamp.prototype.tojson = function() {
return this.toString();
- }
+ };
Timestamp.prototype.getTime = function() {
return this.t;
- }
+ };
Timestamp.prototype.getInc = function() {
return this.i;
- }
+ };
Timestamp.prototype.toString = function() {
return "Timestamp(" + this.t + ", " + this.i + ")";
- }
+ };
}
else {
print("warning: no Timestamp class");
@@ -28,7 +28,7 @@ Date.timeFunc = function(theFunc, numTimes){
}
return (new Date()).getTime() - start.getTime();
-}
+};
Date.prototype.tojson = function(){
var UTC = 'UTC';
@@ -37,10 +37,10 @@ Date.prototype.tojson = function(){
var date = this['get'+UTC+'Date']().zeroPad(2);
var hour = this['get'+UTC+'Hours']().zeroPad(2);
var minute = this['get'+UTC+'Minutes']().zeroPad(2);
- var sec = this['get'+UTC+'Seconds']().zeroPad(2)
+ var sec = this['get'+UTC+'Seconds']().zeroPad(2);
if (this['get'+UTC+'Milliseconds']())
- sec += '.' + this['get'+UTC+'Milliseconds']().zeroPad(3)
+ sec += '.' + this['get'+UTC+'Milliseconds']().zeroPad(3);
var ofs = 'Z';
// // print a non-UTC time
@@ -51,7 +51,7 @@ Date.prototype.tojson = function(){
// ofs += (ofsmin%60).zeroPad(2)
// }
return 'ISODate("'+year+'-'+month+'-'+date+'T'+hour+':'+minute+':'+sec+ofs+'")';
-}
+};
ISODate = function(isoDateStr){
if (!isoDateStr)
@@ -101,16 +101,16 @@ ISODate = function(isoDateStr){
if (res[12] == '+') // if ahead subtract
ofs *= -1;
- time += ofs
+ time += ofs;
}
return new Date(time);
-}
+};
// Regular Expression
RegExp.escape = function(text){
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
-}
+};
RegExp.prototype.tojson = RegExp.prototype.toString;
@@ -125,7 +125,7 @@ Array.contains = function(a, x){
return true;
}
return false;
-}
+};
Array.unique = function(a){
if (!Array.isArray(a)) {
@@ -140,7 +140,7 @@ Array.unique = function(a){
}
}
return u;
-}
+};
Array.shuffle = function(arr){
if (!Array.isArray(arr)) {
@@ -154,7 +154,7 @@ Array.shuffle = function(arr){
arr[pos] = save;
}
return arr;
-}
+};
Array.tojson = function(a, indent, nolint){
if (!Array.isArray(a)) {
@@ -191,7 +191,7 @@ Array.tojson = function(a, indent, nolint){
s += elementSeparator + indent + "]";
return s;
-}
+};
Array.fetchRefs = function(arr, coll){
if (!Array.isArray(arr)) {
@@ -206,7 +206,7 @@ Array.fetchRefs = function(arr, coll){
n.push(z.fetch());
}
return n;
-}
+};
Array.sum = function(arr){
if (!Array.isArray(arr)) {
@@ -219,7 +219,7 @@ Array.sum = function(arr){
for (var i=1; i<arr.length; i++)
s += arr[i];
return s;
-}
+};
Array.avg = function(arr){
if (!Array.isArray(arr)) {
@@ -229,7 +229,7 @@ Array.avg = function(arr){
if (arr.length == 0)
return null;
return Array.sum(arr) / arr.length;
-}
+};
Array.stdDev = function(arr){
if (!Array.isArray(arr)) {
@@ -244,7 +244,7 @@ Array.stdDev = function(arr){
}
return Math.sqrt(sum / arr.length);
-}
+};
// Object
Object.extend = function(dst, src, deep){
@@ -262,12 +262,12 @@ Object.extend = function(dst, src, deep){
dst[k] = v;
}
return dst;
-}
+};
Object.merge = function(dst, src, deep){
- var clone = Object.extend({}, dst, deep)
- return Object.extend(clone, src, deep)
-}
+ var clone = Object.extend({}, dst, deep);
+ return Object.extend(clone, src, deep);
+};
Object.keySet = function(o) {
var ret = new Array();
@@ -277,23 +277,23 @@ Object.keySet = function(o) {
}
}
return ret;
-}
+};
// String
if (String.prototype.trim === undefined) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
- }
+ };
}
if (String.prototype.trimLeft === undefined) {
String.prototype.trimLeft = function() {
return this.replace(/^\s+/,"");
- }
+ };
}
if (String.prototype.trimRight === undefined) {
String.prototype.trimRight = function() {
return this.replace(/\s+$/,"");
- }
+ };
}
// always provide ltrim and rtrim for backwards compatibility
@@ -301,12 +301,12 @@ String.prototype.ltrim = String.prototype.trimLeft;
String.prototype.rtrim = String.prototype.trimRight;
String.prototype.startsWith = function(str){
- return this.indexOf(str) == 0
-}
+ return this.indexOf(str) == 0;
+};
String.prototype.endsWith = function(str){
- return this.indexOf(str, this.length - str.length) !== -1
-}
+ return this.indexOf(str, this.length - str.length) !== -1;
+};
// Polyfill taken from
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
@@ -334,71 +334,71 @@ String.prototype.pad = function(length, right, chr) {
}
}
return str;
-}
+};
// Number
Number.prototype.toPercentStr = function() {
return (this * 100).toFixed(2) + "%";
-}
+};
Number.prototype.zeroPad = function(width) {
return ('' + this).pad(width, false, '0');
-}
+};
// NumberLong
if (! NumberLong.prototype) {
- NumberLong.prototype = {}
+ NumberLong.prototype = {};
}
NumberLong.prototype.tojson = function() {
return this.toString();
-}
+};
// NumberInt
if (! NumberInt.prototype) {
- NumberInt.prototype = {}
+ NumberInt.prototype = {};
}
NumberInt.prototype.tojson = function() {
return this.toString();
-}
+};
// NumberDecimal
if (typeof NumberDecimal !== 'undefined') {
if (! NumberDecimal.prototype) {
- NumberDecimal.prototype = {}
+ NumberDecimal.prototype = {};
}
NumberDecimal.prototype.tojson = function() {
return this.toString();
- }
+ };
}
// ObjectId
if (! ObjectId.prototype)
- ObjectId.prototype = {}
+ ObjectId.prototype = {};
ObjectId.prototype.toString = function(){
return "ObjectId(" + tojson(this.str) + ")";
-}
+};
ObjectId.prototype.tojson = function(){
return this.toString();
-}
+};
ObjectId.prototype.valueOf = function(){
return this.str;
-}
+};
ObjectId.prototype.isObjectId = true;
ObjectId.prototype.getTimestamp = function(){
return new Date(parseInt(this.valueOf().slice(0,8), 16)*1000);
-}
+};
ObjectId.prototype.equals = function(other){
return this.str == other.str;
-}
+};
// Creates an ObjectId from a Date.
// Based on solution discussed here:
@@ -429,7 +429,7 @@ ObjectId.fromDate = function(source) {
var objectId = ObjectId(hexTimestamp);
return objectId;
-}
+};
// DBPointer
if (typeof(DBPointer) != "undefined"){
@@ -437,23 +437,23 @@ if (typeof(DBPointer) != "undefined"){
assert(this.ns, "need a ns");
assert(this.id, "need an id");
return db[ this.ns ].findOne({ _id : this.id });
- }
+ };
DBPointer.prototype.tojson = function(indent){
return this.toString();
- }
+ };
DBPointer.prototype.getCollection = function(){
return this.ns;
- }
+ };
DBPointer.prototype.getId = function(){
return this.id;
- }
+ };
DBPointer.prototype.toString = function(){
return "DBPointer(" + tojson(this.ns) + ", " + tojson(this.id) + ")";
- }
+ };
}
else {
print("warning: no DBPointer");
@@ -466,31 +466,31 @@ if (typeof(DBRef) != "undefined"){
assert(this.$id, "need an id");
var coll = this.$db ? db.getSiblingDB(this.$db).getCollection(this.$ref) : db[this.$ref];
return coll.findOne({ _id : this.$id });
- }
+ };
DBRef.prototype.tojson = function(indent){
return this.toString();
- }
+ };
DBRef.prototype.getDb = function(){
return this.$db || undefined;
- }
+ };
DBRef.prototype.getCollection = function(){
return this.$ref;
- }
+ };
DBRef.prototype.getRef = function(){
return this.$ref;
- }
+ };
DBRef.prototype.getId = function(){
return this.$id;
- }
+ };
DBRef.prototype.toString = function(){
return "DBRef(" + tojson(this.$ref) + ", " + tojson(this.$id) + (this.$db ? ", " + tojson(this.$db) : "") + ")";
- }
+ };
}
else {
print("warning: no DBRef");
@@ -500,14 +500,14 @@ else {
if (typeof(BinData) != "undefined"){
BinData.prototype.tojson = function() {
return this.toString();
- }
+ };
BinData.prototype.subtype = function() {
return this.type;
- }
+ };
BinData.prototype.length = function() {
return this.len;
- }
+ };
}
else {
print("warning: no BinData class");
@@ -517,7 +517,7 @@ else {
if (typeof(Map) == "undefined"){
Map = function(){
this._data = {};
- }
+ };
}
Map.hash = function(val){
@@ -539,18 +539,18 @@ Map.hash = function(val){
}
throw Error( "can't hash : " + typeof(val) );
-}
+};
Map.prototype.put = function(key, value){
var o = this._get(key);
var old = o.value;
o.value = value;
return old;
-}
+};
Map.prototype.get = function(key){
return this._get(key).value;
-}
+};
Map.prototype._get = function(key){
var h = Map.hash(key);
@@ -567,7 +567,7 @@ Map.prototype._get = function(key){
var o = { key : key, value : null };
a.push(o);
return o;
-}
+};
Map.prototype.values = function(){
var all = [];
@@ -575,18 +575,18 @@ Map.prototype.values = function(){
this._data[k].forEach(function(z){ all.push(z.value); });
}
return all;
-}
+};
if (typeof(gc) == "undefined"){
gc = function(){
print("warning: using noop gc()");
- }
+ };
}
// Free Functions
tojsononeline = function(x){
return tojson(x, " ", true);
-}
+};
tojson = function(x, indent, nolint){
if (x === null)
@@ -658,7 +658,7 @@ tojson = function(x, indent, nolint){
throw Error( "tojson can't handle type " + (typeof x) );
}
-}
+};
tojsonObject = function(x, indent, nolint){
var lineEnding = nolint ? " " : "\n";
@@ -720,25 +720,25 @@ tojsonObject = function(x, indent, nolint){
// pop one level of indent
indent = indent.substring(1);
return s + indent + "}";
-}
+};
printjson = function(x){
print( tojson( x ) );
-}
+};
printjsononeline = function(x){
print( tojsononeline( x ) );
-}
+};
isString = function(x){
return typeof(x) == "string";
-}
+};
isNumber = function(x){
return typeof(x) == "number";
-}
+};
// This function returns true even if the argument is an array. See SERVER-14220.
isObject = function(x){
return typeof(x) == "object";
-}
+};
diff --git a/src/mongo/shell/utils.js b/src/mongo/shell/utils.js
index 55c6367fe25..d5f5932d453 100644
--- a/src/mongo/shell/utils.js
+++ b/src/mongo/shell/utils.js
@@ -1,12 +1,12 @@
__quiet = false;
-__magicNoPrint = { __magicNoPrint : 1111 }
+__magicNoPrint = { __magicNoPrint : 1111 };
__callLastError = false;
_verboseShell = false;
chatty = function(s){
if ( ! __quiet )
print( s );
-}
+};
function reconnect(db) {
assert.soon(function() {
@@ -17,7 +17,7 @@ function reconnect(db) {
return false;
}
});
-};
+}
function _getErrorWithCode(codeOrObj, message) {
var e = new Error(message);
@@ -49,7 +49,7 @@ friendlyEqual = function( a , b ){
var clean = function( s ){
s = s.replace( /NumberInt\((\-?\d+)\)/g , "$1" );
return s;
- }
+ };
a = clean(a);
b = clean(b);
@@ -58,7 +58,7 @@ friendlyEqual = function( a , b ){
return true;
return false;
-}
+};
printStackTrace = function(){
try{
@@ -66,7 +66,7 @@ printStackTrace = function(){
} catch (e) {
print(e.stack);
}
-}
+};
/**
* <p> Set the shell verbosity. If verbose the shell will display more information about command results. </>
@@ -76,14 +76,14 @@ printStackTrace = function(){
setVerboseShell = function( value ) {
if( value == undefined ) value = true;
_verboseShell = value;
-}
+};
argumentsToArray = function( a ){
var arr = [];
for ( var i=0; i<a.length; i++ )
arr[i] = a[i];
return arr;
-}
+};
// Formats a simple stacked horizontal histogram bar in the shell.
// @param data array of the form [[ratio, symbol], ...] where ratio is between 0 and 1 and
@@ -106,16 +106,16 @@ _barFormat = function(data, width) {
}
res += "]";
return res;
-}
+};
//these two are helpers for Array.sort(func)
-compare = function(l, r){ return (l == r ? 0 : (l < r ? -1 : 1)); }
+compare = function(l, r){ return (l == r ? 0 : (l < r ? -1 : 1)); };
// arr.sort(compareOn('name'))
compareOn = function(field){
- return function(l, r) { return compare(l[field], r[field]); }
-}
+ return function(l, r) { return compare(l[field], r[field]); };
+};
shellPrint = function( x ){
@@ -133,7 +133,7 @@ shellPrint = function( x ){
}
db.resetError();
}
-}
+};
print.captureAllOutput = function (fn, args) {
var res = {};
@@ -153,13 +153,13 @@ print.captureAllOutput = function (fn, args) {
};
if ( typeof TestData == "undefined" ){
- TestData = undefined
+ TestData = undefined;
}
jsTestName = function(){
- if( TestData ) return TestData.testName
- return "__unknown_name__"
-}
+ if( TestData ) return TestData.testName;
+ return "__unknown_name__";
+};
var _jsTestOptions = { enableTestCommands : true }; // Test commands should be enabled by default
@@ -196,25 +196,25 @@ jsTestOptions = function(){
);
}
return _jsTestOptions;
-}
+};
setJsTestOption = function(name, value) {
_jsTestOptions[name] = value;
-}
+};
jsTestLog = function(msg){
- print( "\n\n----\n" + msg + "\n----\n\n" )
-}
+ print( "\n\n----\n" + msg + "\n----\n\n" );
+};
-jsTest = {}
+jsTest = {};
-jsTest.name = jsTestName
-jsTest.options = jsTestOptions
-jsTest.setOption = setJsTestOption
-jsTest.log = jsTestLog
-jsTest.readOnlyUserRoles = ["read"]
-jsTest.basicUserRoles = ["dbOwner"]
-jsTest.adminUserRoles = ["root"]
+jsTest.name = jsTestName;
+jsTest.options = jsTestOptions;
+jsTest.setOption = setJsTestOption;
+jsTest.log = jsTestLog;
+jsTest.readOnlyUserRoles = ["read"];
+jsTest.basicUserRoles = ["dbOwner"];
+jsTest.adminUserRoles = ["root"];
jsTest.authenticate = function(conn) {
if (!jsTest.options().auth && !jsTest.options().keyFile) {
@@ -241,7 +241,7 @@ jsTest.authenticate = function(conn) {
conn.authenticated = false;
}
return conn.authenticated;
-}
+};
jsTest.authenticateNodes = function(nodes) {
assert.soon(function() {
@@ -257,11 +257,11 @@ jsTest.authenticateNodes = function(nodes) {
}
return true;
}, "Authenticate to nodes: " + nodes, 30000);
-}
+};
jsTest.isMongos = function(conn) {
return conn.getDB('admin').isMaster().msg=='isdbgrid';
-}
+};
defaultPrompt = function() {
var status = db.getMongo().authStatus;
@@ -272,7 +272,7 @@ defaultPrompt = function() {
var buildInfo = db.runCommand({buildInfo: 1});
try {
if (buildInfo.modules.indexOf("enterprise") > -1) {
- prefix = "MongoDB Enterprise "
+ prefix = "MongoDB Enterprise ";
}
} catch (e) {
// Don't do anything here. Just throw the error away.
@@ -332,7 +332,7 @@ defaultPrompt = function() {
db.getMongo().authStatus = status;
return prefix + "> ";
-}
+};
replSetMemberStatePrompt = function() {
var state = '';
@@ -358,7 +358,7 @@ replSetMemberStatePrompt = function() {
}
}
return state + '> ';
-}
+};
isMasterStatePrompt = function() {
var state = '';
@@ -378,7 +378,7 @@ isMasterStatePrompt = function() {
else if (isMaster.arbiterOnly)
role = "ARBITER";
else {
- role = "OTHER"
+ role = "OTHER";
}
state = isMaster.setName + ':';
}
@@ -387,22 +387,22 @@ isMasterStatePrompt = function() {
throw _getErrorWithCode(isMaster, "Failed: " + tojson(isMaster));
}
return state + '> ';
-}
+};
if (typeof(_useWriteCommandsDefault) == 'undefined') {
// This is for cases when the v8 engine is used other than the mongo shell, like map reduce.
_useWriteCommandsDefault = function() { return false; };
-};
+}
if (typeof(_writeMode) == 'undefined') {
// This is for cases when the v8 engine is used other than the mongo shell, like map reduce.
_writeMode = function() { return "commands"; };
-};
+}
if (typeof(_readMode) == 'undefined') {
// This is for cases when the v8 engine is used other than the mongo shell, like map reduce.
_readMode = function() { return "legacy"; };
-};
+}
shellPrintHelper = function (x) {
if (typeof (x) == "undefined") {
@@ -445,7 +445,7 @@ shellPrintHelper = function (x) {
print(x.tojson());
else
print(tojson(x));
-}
+};
shellAutocomplete = function ( /*prefix*/ ) { // outer scope function called on init. Actual function at end
@@ -479,7 +479,7 @@ shellAutocomplete = function ( /*prefix*/ ) { // outer scope function called on
if ( name[0] == '_' ) return true;
if ( name[name.length - 1] == '_' ) return true; // some native functions have an extra name_ method
return false;
- }
+ };
var customComplete = function( obj ) {
try {
@@ -497,7 +497,7 @@ shellAutocomplete = function ( /*prefix*/ ) { // outer scope function called on
// print( e ); // uncomment if debugging custom completers
return [];
}
- }
+ };
var worker = function( prefix ) {
var global = ( function() { return this; } ).call(); // trick to get global object
@@ -511,7 +511,7 @@ shellAutocomplete = function ( /*prefix*/ ) { // outer scope function called on
}
var lastPrefix = parts[parts.length - 1] || '';
- var lastPrefixLowercase = lastPrefix.toLowerCase()
+ var lastPrefixLowercase = lastPrefix.toLowerCase();
var beginning = parts.slice( 0, parts.length - 1 ).join( '.' );
if ( beginning.length )
beginning += '.';
@@ -547,7 +547,7 @@ shellAutocomplete = function ( /*prefix*/ ) { // outer scope function called on
ret.push( i );
return ret;
- }
+ };
// this is the actual function that gets assigned to shellAutocomplete
return function( prefix ) {
@@ -557,7 +557,7 @@ shellAutocomplete = function ( /*prefix*/ ) { // outer scope function called on
print( "exception during autocomplete: " + tojson( e.message ) );
__autocomplete__ = [];
}
- }
+ };
} ();
shellAutocomplete.showPrivate = false; // toggle to show (useful when working on internals)
@@ -574,7 +574,7 @@ shellHelper = function( command , rest , shouldPrint ){
shellPrintHelper( res );
}
return res;
-}
+};
shellHelper.use = function (dbname) {
var s = "" + dbname;
@@ -584,7 +584,7 @@ shellHelper.use = function (dbname) {
}
db = db.getMongo().getDB(dbname);
print("switched to db " + db.getName());
-}
+};
shellHelper.set = function (str) {
if (str == "") {
@@ -604,7 +604,7 @@ shellHelper.set = function (str) {
_verboseShell = value;
}
print("set " + param + " to " + value);
-}
+};
shellHelper.it = function(){
if ( typeof( ___it___ ) == "undefined" || ___it___ == null ){
@@ -612,14 +612,14 @@ shellHelper.it = function(){
return;
}
shellPrintHelper( ___it___ );
-}
+};
shellHelper.show = function (what) {
assert(typeof what == "string");
var args = what.split( /\s+/ );
- what = args[0]
- args = args.splice(1)
+ what = args[0];
+ args = args.splice(1);
if (what == "profile") {
if (db.system.profile.count() == 0) {
@@ -654,7 +654,7 @@ shellHelper.show = function (what) {
print( l );
print("\n");
}
- )
+ );
}
return "";
}
@@ -670,7 +670,7 @@ shellHelper.show = function (what) {
}
if (what == "collections" || what == "tables") {
- db.getCollectionNames().forEach(function (x) { print(x) });
+ db.getCollectionNames().forEach(function (x) { print(x); });
return "";
}
@@ -697,7 +697,7 @@ shellHelper.show = function (what) {
});
});
- dbinfo.sort(compareOn('name'))
+ dbinfo.sort(compareOn('name'));
dbinfo.forEach(function (db) {
var namePadding = maxNameLength - db.name_size;
var sizePadding = maxGbDigits - db.gb_digits;
@@ -715,7 +715,7 @@ shellHelper.show = function (what) {
if (what == "log" ) {
var n = "global";
if ( args.length > 0 )
- n = args[0]
+ n = args[0];
var res = db.adminCommand( { getLog : n } );
if ( ! res.ok ) {
@@ -723,21 +723,21 @@ shellHelper.show = function (what) {
return "";
}
for ( var i=0; i<res.log.length; i++){
- print( res.log[i] )
+ print( res.log[i] );
}
- return ""
+ return "";
}
if (what == "logs" ) {
- var res = db.adminCommand( { getLog : "*" } )
+ var res = db.adminCommand( { getLog : "*" } );
if ( ! res.ok ) {
print("Error while trying to show logs: " + res.errmsg);
return "";
}
for ( var i=0; i<res.names.length; i++){
- print( res.names[i] )
+ print( res.names[i] );
}
- return ""
+ return "";
}
if (what == "startupWarnings" ) {
@@ -757,7 +757,7 @@ shellHelper.show = function (what) {
}
print( "Server has startup warnings: " );
for ( var i=0; i<res.log.length; i++){
- print( res.log[i] )
+ print( res.log[i] );
}
return "";
} else if (res.errmsg == "no such cmd: getLog" ) {
@@ -780,7 +780,7 @@ shellHelper.show = function (what) {
throw Error( "don't know how to show [" + what + "]" );
-}
+};
Math.sigFig = function( x , N ){
if ( ! N ){
@@ -788,7 +788,7 @@ Math.sigFig = function( x , N ){
}
var p = Math.pow( 10, N - Math.ceil( Math.log( Math.abs(x) ) / Math.log( 10 )) );
return Math.round(x*p)/p;
-}
+};
var Random = (function() {
var initialized = false;
@@ -893,7 +893,7 @@ Geo.distance = function( a , b ){
return Math.sqrt( Math.pow( by - ay , 2 ) +
Math.pow( bx - ax , 2 ) );
-}
+};
Geo.sphereDistance = function( a , b ){
var ax = null;
@@ -933,9 +933,9 @@ Geo.sphereDistance = function( a , b ){
}
return Math.acos(cross_prod);
-}
+};
-rs = function () { return "try rs.help()"; }
+rs = function () { return "try rs.help()"; };
/**
* This method is intended to aid in the writing of tests. It takes a host's address, desired state,
@@ -951,7 +951,7 @@ _awaitRSHostViaRSMonitor = function(hostAddr, desiredState, rsName, timeout) {
desiredState = {ok: true};
}
- print("Awaiting " + hostAddr + " to be " + tojson(desiredState) + " in " + " rs " + rsName)
+ print("Awaiting " + hostAddr + " to be " + tojson(desiredState) + " in " + " rs " + rsName);
var tests = 0;
assert.soon(function() {
@@ -961,7 +961,7 @@ _awaitRSHostViaRSMonitor = function(hostAddr, desiredState, rsName, timeout) {
}
for (var i=0; i<stats.length; i++) {
- var node = stats[i]
+ var node = stats[i];
printjson(node);
if (node["addr"] !== hostAddr)
continue;
@@ -989,7 +989,7 @@ _awaitRSHostViaRSMonitor = function(hostAddr, desiredState, rsName, timeout) {
}, "timed out waiting for replica set member: " + hostAddr + " to reach state: " +
tojson(desiredState),
timeout);
-}
+};
rs.help = function () {
print("\trs.status() { replSetGetStatus : 1 } checks repl set status");
@@ -1012,13 +1012,13 @@ rs.help = function () {
print();
print("\treconfiguration helpers disconnect from the database so the shell will display");
print("\tan error, even if the command succeeds.");
-}
-rs.slaveOk = function (value) { return db.getMongo().setSlaveOk(value); }
-rs.status = function () { return db._adminCommand("replSetGetStatus"); }
-rs.isMaster = function () { return db.isMaster(); }
-rs.initiate = function (c) { return db._adminCommand({ replSetInitiate: c }); }
-rs.printSlaveReplicationInfo = function () { return db.printSlaveReplicationInfo() };
-rs.printReplicationInfo = function () { return db.printReplicationInfo() };
+};
+rs.slaveOk = function (value) { return db.getMongo().setSlaveOk(value); };
+rs.status = function () { return db._adminCommand("replSetGetStatus"); };
+rs.isMaster = function () { return db.isMaster(); };
+rs.initiate = function (c) { return db._adminCommand({ replSetInitiate: c }); };
+rs.printSlaveReplicationInfo = function () { return db.printSlaveReplicationInfo(); };
+rs.printReplicationInfo = function () { return db.printReplicationInfo(); };
rs._runCmd = function (c) {
// after the command, catch the disconnect and reconnect if necessary
var res = null;
@@ -1044,7 +1044,7 @@ rs._runCmd = function (c) {
return "";
}
return res;
-}
+};
rs.reconfig = function (cfg, options) {
cfg.version = rs.conf().version + 1;
cmd = { replSetReconfig: cfg };
@@ -1052,7 +1052,7 @@ rs.reconfig = function (cfg, options) {
cmd[i] = options[i];
}
return this._runCmd(cmd);
-}
+};
rs.add = function (hostport, arb) {
var cfg = hostport;
@@ -1081,7 +1081,7 @@ rs.add = function (hostport, arb) {
}
c.members.push(cfg);
return this._runCmd({ replSetReconfig: c });
-}
+};
rs.syncFrom = function (host) { return db._adminCommand({replSetSyncFrom : host}); };
rs.stepDown = function (stepdownSecs, catchUpSecs) {
var cmdObj = {replSetStepDown: stepdownSecs === undefined ? 60 : stepdownSecs};
@@ -1090,8 +1090,8 @@ rs.stepDown = function (stepdownSecs, catchUpSecs) {
}
return db._adminCommand(cmdObj);
};
-rs.freeze = function (secs) { return db._adminCommand({replSetFreeze:secs}); }
-rs.addArb = function (hn) { return this.add(hn, true); }
+rs.freeze = function (secs) { return db._adminCommand({replSetFreeze:secs}); };
+rs.addArb = function (hn) { return this.add(hn, true); };
rs.conf = function () {
var resp = db._adminCommand({replSetGetConfig:1});
@@ -1100,7 +1100,7 @@ rs.conf = function () {
else if (resp.errmsg && resp.errmsg.startsWith("no such cmd"))
return db.getSisterDB("local").system.replset.findOne();
throw new Error("Could not retrieve replica set config: " + tojson(resp));
-}
+};
rs.config = rs.conf;
rs.remove = function (hn) {
@@ -1265,4 +1265,4 @@ help = shellHelper.help = function (x) {
}
else
print("unknown help option");
-}
+};
diff --git a/src/mongo/shell/utils_sh.js b/src/mongo/shell/utils_sh.js
index 6da3f3da259..385d1e6ff2d 100644
--- a/src/mongo/shell/utils_sh.js
+++ b/src/mongo/shell/utils_sh.js
@@ -1,44 +1,44 @@
-sh = function() { return "try sh.help();" }
+sh = function() { return "try sh.help();"; };
sh._checkMongos = function() {
var x = db.runCommand( "ismaster" );
if ( x.msg != "isdbgrid" )
throw Error("not connected to a mongos");
-}
+};
sh._checkFullName = function( fullName ) {
- assert( fullName , "need a full name" )
- assert( fullName.indexOf( "." ) > 0 , "name needs to be fully qualified <db>.<collection>'" )
-}
+ assert( fullName , "need a full name" );
+ assert( fullName.indexOf( "." ) > 0 , "name needs to be fully qualified <db>.<collection>'" );
+};
sh._adminCommand = function( cmd , skipCheck ) {
if ( ! skipCheck ) sh._checkMongos();
return db.getSisterDB( "admin" ).runCommand( cmd );
-}
+};
sh._getConfigDB = function() {
sh._checkMongos();
return db.getSiblingDB( "config" );
-}
+};
sh._dataFormat = function( bytes ){
- if( bytes < 1024 ) return Math.floor( bytes ) + "B"
- if( bytes < 1024 * 1024 ) return Math.floor( bytes / 1024 ) + "KiB"
- if( bytes < 1024 * 1024 * 1024 ) return Math.floor( ( Math.floor( bytes / 1024 ) / 1024 ) * 100 ) / 100 + "MiB"
- return Math.floor( ( Math.floor( bytes / ( 1024 * 1024 ) ) / 1024 ) * 100 ) / 100 + "GiB"
-}
+ if( bytes < 1024 ) return Math.floor( bytes ) + "B";
+ if( bytes < 1024 * 1024 ) return Math.floor( bytes / 1024 ) + "KiB";
+ if( bytes < 1024 * 1024 * 1024 ) return Math.floor( ( Math.floor( bytes / 1024 ) / 1024 ) * 100 ) / 100 + "MiB";
+ return Math.floor( ( Math.floor( bytes / ( 1024 * 1024 ) ) / 1024 ) * 100 ) / 100 + "GiB";
+};
sh._collRE = function( coll ){
- return RegExp( "^" + RegExp.escape(coll + "") + "-.*" )
-}
+ return RegExp( "^" + RegExp.escape(coll + "") + "-.*" );
+};
sh._pchunk = function( chunk ){
- return "[" + tojson( chunk.min ) + " -> " + tojson( chunk.max ) + "]"
-}
+ return "[" + tojson( chunk.min ) + " -> " + tojson( chunk.max ) + "]";
+};
sh.help = function() {
- print( "\tsh.addShard( host ) server:port OR setname/server:port" )
- print( "\tsh.enableSharding(dbname) enables sharding on the database dbname" )
+ print( "\tsh.addShard( host ) server:port OR setname/server:port" );
+ print( "\tsh.enableSharding(dbname) enables sharding on the database dbname" );
print( "\tsh.shardCollection(fullName,key,unique) shards the collection" );
print( "\tsh.splitFind(fullName,find) splits the chunk that find is in at the median" );
@@ -57,62 +57,62 @@ sh.help = function() {
print( "\tsh.addTagRange(fullName,min,max,tag) tags the specified range of the given collection" );
print( "\tsh.removeTagRange(fullName,min,max,tag) removes the tagged range of the given collection" );
- print( "\tsh.status() prints a general overview of the cluster" )
-}
+ print( "\tsh.status() prints a general overview of the cluster" );
+};
sh.status = function( verbose , configDB ) {
// TODO: move the actual command here
printShardingStatus( configDB , verbose );
-}
+};
sh.addShard = function( url ){
return sh._adminCommand( { addShard : url } , true );
-}
+};
sh.enableSharding = function( dbname ) {
- assert( dbname , "need a valid dbname" )
+ assert( dbname , "need a valid dbname" );
return sh._adminCommand( { enableSharding : dbname } );
-}
+};
sh.shardCollection = function( fullName , key , unique ) {
- sh._checkFullName( fullName )
- assert( key , "need a key" )
- assert( typeof( key ) == "object" , "key needs to be an object" )
+ sh._checkFullName( fullName );
+ assert( key , "need a key" );
+ assert( typeof( key ) == "object" , "key needs to be an object" );
- var cmd = { shardCollection : fullName , key : key }
+ var cmd = { shardCollection : fullName , key : key };
if ( unique )
cmd.unique = true;
return sh._adminCommand( cmd );
-}
+};
sh.splitFind = function( fullName , find ) {
- sh._checkFullName( fullName )
+ sh._checkFullName( fullName );
return sh._adminCommand( { split : fullName , find : find } );
-}
+};
sh.splitAt = function( fullName , middle ) {
- sh._checkFullName( fullName )
+ sh._checkFullName( fullName );
return sh._adminCommand( { split : fullName , middle : middle } );
-}
+};
sh.moveChunk = function( fullName , find , to ) {
sh._checkFullName( fullName );
- return sh._adminCommand( { moveChunk : fullName , find : find , to : to } )
-}
+ return sh._adminCommand( { moveChunk : fullName , find : find , to : to } );
+};
sh.setBalancerState = function( onOrNot ) {
sh._getConfigDB().settings.update({ _id: "balancer" }, { $set : { stopped: onOrNot ? false : true } }, true );
-}
+};
sh.getBalancerState = function(configDB) {
if (configDB === undefined)
configDB = sh._getConfigDB();
- var x = configDB.settings.findOne({ _id: "balancer" } )
+ var x = configDB.settings.findOne({ _id: "balancer" } );
if ( x == null )
return true;
return ! x.stopped;
-}
+};
sh.isBalancerRunning = function (configDB) {
if (configDB === undefined)
@@ -123,7 +123,7 @@ sh.isBalancerRunning = function (configDB) {
return false;
}
return x.state > 0;
-}
+};
sh.getBalancerHost = function(configDB) {
if (configDB === undefined)
@@ -131,42 +131,42 @@ sh.getBalancerHost = function(configDB) {
var x = configDB.locks.findOne({ _id: "balancer" });
if( x == null ){
print("config.locks collection does not contain balancer lock. be sure you are connected to a mongos");
- return ""
+ return "";
}
- return x.process.match(/[^:]+:[^:]+/)[0]
-}
+ return x.process.match(/[^:]+:[^:]+/)[0];
+};
sh.stopBalancer = function( timeout, interval ) {
- sh.setBalancerState( false )
- sh.waitForBalancer( false, timeout, interval )
-}
+ sh.setBalancerState( false );
+ sh.waitForBalancer( false, timeout, interval );
+};
sh.startBalancer = function( timeout, interval ) {
- sh.setBalancerState( true )
- sh.waitForBalancer( true, timeout, interval )
-}
+ sh.setBalancerState( true );
+ sh.waitForBalancer( true, timeout, interval );
+};
sh.waitForDLock = function( lockId, onOrNot, timeout, interval ){
// Wait for balancer to be on or off
// Can also wait for particular balancer state
- var state = onOrNot
+ var state = onOrNot;
var configDB = sh._getConfigDB();
- var beginTS = undefined
+ var beginTS = undefined;
if( state == undefined ){
- var currLock = configDB.locks.findOne({ _id : lockId })
- if( currLock != null ) beginTS = currLock.ts
+ var currLock = configDB.locks.findOne({ _id : lockId });
+ if( currLock != null ) beginTS = currLock.ts;
}
var lockStateOk = function(){
- var lock = configDB.locks.findOne({ _id : lockId })
+ var lock = configDB.locks.findOne({ _id : lockId });
- if( state == false ) return ! lock || lock.state == 0
- if( state == true ) return lock && lock.state == 2
+ if( state == false ) return ! lock || lock.state == 0;
+ if( state == true ) return lock && lock.state == 2;
if( state == undefined ) return (beginTS == undefined && lock) ||
- (beginTS != undefined && ( !lock || lock.ts + "" != beginTS + "" ) )
- else return lock && lock.state == state
- }
+ (beginTS != undefined && ( !lock || lock.ts + "" != beginTS + "" ) );
+ else return lock && lock.state == state;
+ };
assert.soon( lockStateOk,
"Waited too long for lock " + lockId + " to " +
@@ -174,27 +174,27 @@ sh.waitForDLock = function( lockId, onOrNot, timeout, interval ){
"change to state " + state ) ),
timeout,
interval
- )
-}
+ );
+};
sh.waitForPingChange = function( activePings, timeout, interval ){
var isPingChanged = function( activePing ){
- var newPing = sh._getConfigDB().mongos.findOne({ _id : activePing._id })
- return ! newPing || newPing.ping + "" != activePing.ping + ""
- }
+ var newPing = sh._getConfigDB().mongos.findOne({ _id : activePing._id });
+ return ! newPing || newPing.ping + "" != activePing.ping + "";
+ };
// First wait for all active pings to change, so we're sure a settings reload
// happened
// Timeout all pings on the same clock
- var start = new Date()
+ var start = new Date();
- var remainingPings = []
+ var remainingPings = [];
for( var i = 0; i < activePings.length; i++ ){
- var activePing = activePings[ i ]
- print( "Waiting for active host " + activePing._id + " to recognize new settings... (ping : " + activePing.ping + ")" )
+ var activePing = activePings[ i ];
+ print( "Waiting for active host " + activePing._id + " to recognize new settings... (ping : " + activePing.ping + ")" );
// Do a manual timeout here, avoid scary assert.soon errors
var timeout = timeout || 30000;
@@ -202,57 +202,57 @@ sh.waitForPingChange = function( activePings, timeout, interval ){
while( isPingChanged( activePing ) != true ){
if( ( new Date() ).getTime() - start.getTime() > timeout ){
print( "Waited for active ping to change for host " + activePing._id +
- ", a migration may be in progress or the host may be down." )
- remainingPings.push( activePing )
- break
+ ", a migration may be in progress or the host may be down." );
+ remainingPings.push( activePing );
+ break;
}
- sleep( interval )
+ sleep( interval );
}
}
- return remainingPings
-}
+ return remainingPings;
+};
sh.waitForBalancerOff = function( timeout, interval ){
- var pings = sh._getConfigDB().mongos.find().toArray()
- var activePings = []
+ var pings = sh._getConfigDB().mongos.find().toArray();
+ var activePings = [];
for( var i = 0; i < pings.length; i++ ){
- if( ! pings[i].waiting ) activePings.push( pings[i] )
+ if( ! pings[i].waiting ) activePings.push( pings[i] );
}
- print( "Waiting for active hosts..." )
+ print( "Waiting for active hosts..." );
- activePings = sh.waitForPingChange( activePings, 60 * 1000 )
+ activePings = sh.waitForPingChange( activePings, 60 * 1000 );
// After 1min, we assume that all hosts with unchanged pings are either
// offline (this is enough time for a full errored balance round, if a network
// issue, which would reload settings) or balancing, which we wait for next
// Legacy hosts we always have to wait for
- print( "Waiting for the balancer lock..." )
+ print( "Waiting for the balancer lock..." );
// Wait for the balancer lock to become inactive
// We can guess this is stale after 15 mins, but need to double-check manually
try{
- sh.waitForDLock( "balancer", false, 15 * 60 * 1000 )
+ sh.waitForDLock( "balancer", false, 15 * 60 * 1000 );
}
catch( e ){
- print( "Balancer still may be active, you must manually verify this is not the case using the config.changelog collection." )
+ print( "Balancer still may be active, you must manually verify this is not the case using the config.changelog collection." );
throw Error(e);
}
- print( "Waiting again for active hosts after balancer is off..." )
+ print( "Waiting again for active hosts after balancer is off..." );
// Wait a short time afterwards, to catch the host which was balancing earlier
- activePings = sh.waitForPingChange( activePings, 5 * 1000 )
+ activePings = sh.waitForPingChange( activePings, 5 * 1000 );
// Warn about all the stale host pings remaining
for( var i = 0; i < activePings.length; i++ ){
- print( "Warning : host " + activePings[i]._id + " seems to have been offline since " + activePings[i].ping )
+ print( "Warning : host " + activePings[i]._id + " seems to have been offline since " + activePings[i].ping );
}
-}
+};
sh.waitForBalancer = function( onOrNot, timeout, interval ){
@@ -261,96 +261,96 @@ sh.waitForBalancer = function( onOrNot, timeout, interval ){
if( onOrNot ){
// Just wait for the balancer lock to change, can't ensure we'll ever see it
// actually locked
- sh.waitForDLock( "balancer", undefined, timeout, interval )
+ sh.waitForDLock( "balancer", undefined, timeout, interval );
}
else {
// Otherwise we need to wait until we're sure balancing stops
- sh.waitForBalancerOff( timeout, interval )
+ sh.waitForBalancerOff( timeout, interval );
}
-}
+};
sh.disableBalancing = function( coll ){
if (coll === undefined) {
throw Error("Must specify collection");
}
- var dbase = db
+ var dbase = db;
if( coll instanceof DBCollection ) {
- dbase = coll.getDB()
+ dbase = coll.getDB();
} else {
sh._checkMongos();
}
- dbase.getSisterDB( "config" ).collections.update({ _id : coll + "" }, { $set : { "noBalance" : true } })
-}
+ dbase.getSisterDB( "config" ).collections.update({ _id : coll + "" }, { $set : { "noBalance" : true } });
+};
sh.enableBalancing = function( coll ){
if (coll === undefined) {
throw Error("Must specify collection");
}
- var dbase = db
+ var dbase = db;
if( coll instanceof DBCollection ) {
- dbase = coll.getDB()
+ dbase = coll.getDB();
} else {
sh._checkMongos();
}
- dbase.getSisterDB( "config" ).collections.update({ _id : coll + "" }, { $set : { "noBalance" : false } })
-}
+ dbase.getSisterDB( "config" ).collections.update({ _id : coll + "" }, { $set : { "noBalance" : false } });
+};
/*
* Can call _lastMigration( coll ), _lastMigration( db ), _lastMigration( st ), _lastMigration( mongos )
*/
sh._lastMigration = function( ns ){
- var coll = null
- var dbase = null
- var config = null
+ var coll = null;
+ var dbase = null;
+ var config = null;
if( ! ns ){
- config = db.getSisterDB( "config" )
+ config = db.getSisterDB( "config" );
}
else if( ns instanceof DBCollection ){
- coll = ns
- config = coll.getDB().getSisterDB( "config" )
+ coll = ns;
+ config = coll.getDB().getSisterDB( "config" );
}
else if( ns instanceof DB ){
- dbase = ns
- config = dbase.getSisterDB( "config" )
+ dbase = ns;
+ config = dbase.getSisterDB( "config" );
}
else if( ns instanceof ShardingTest ){
- config = ns.s.getDB( "config" )
+ config = ns.s.getDB( "config" );
}
else if( ns instanceof Mongo ){
- config = ns.getDB( "config" )
+ config = ns.getDB( "config" );
}
else {
// String namespace
- ns = ns + ""
+ ns = ns + "";
if( ns.indexOf( "." ) > 0 ){
- config = db.getSisterDB( "config" )
- coll = db.getMongo().getCollection( ns )
+ config = db.getSisterDB( "config" );
+ coll = db.getMongo().getCollection( ns );
}
else{
- config = db.getSisterDB( "config" )
- dbase = db.getSisterDB( ns )
+ config = db.getSisterDB( "config" );
+ dbase = db.getSisterDB( ns );
}
}
- var searchDoc = { what : /^moveChunk/ }
- if( coll ) searchDoc.ns = coll + ""
- if( dbase ) searchDoc.ns = new RegExp( "^" + dbase + "\\." )
+ var searchDoc = { what : /^moveChunk/ };
+ if( coll ) searchDoc.ns = coll + "";
+ if( dbase ) searchDoc.ns = new RegExp( "^" + dbase + "\\." );
- var cursor = config.changelog.find( searchDoc ).sort({ time : -1 }).limit( 1 )
- if( cursor.hasNext() ) return cursor.next()
- else return null
-}
+ var cursor = config.changelog.find( searchDoc ).sort({ time : -1 }).limit( 1 );
+ if( cursor.hasNext() ) return cursor.next();
+ else return null;
+};
sh._checkLastError = function( mydb ) {
var errObj = mydb.getLastErrorObj();
if (errObj.err)
throw _getErrorWithCode(errObj, "error: " + errObj.err);
-}
+};
sh.addShardTag = function( shard, tag ) {
var config = sh._getConfigDB();
@@ -359,7 +359,7 @@ sh.addShardTag = function( shard, tag ) {
}
config.shards.update( { _id : shard } , { $addToSet : { tags : tag } } );
sh._checkLastError( config );
-}
+};
sh.removeShardTag = function( shard, tag ) {
var config = sh._getConfigDB();
@@ -368,7 +368,7 @@ sh.removeShardTag = function( shard, tag ) {
}
config.shards.update( { _id : shard } , { $pull : { tags : tag } } );
sh._checkLastError( config );
-}
+};
sh.addTagRange = function( ns, min, max, tag ) {
if ( bsonWoCompare( min, max ) == 0 ) {
@@ -380,7 +380,7 @@ sh.addTagRange = function( ns, min, max, tag ) {
{_id: { ns : ns , min : min }, ns : ns , min : min , max : max , tag : tag } ,
true );
sh._checkLastError( config );
-}
+};
sh.removeTagRange = function( ns, min, max, tag ) {
var config = sh._getConfigDB();
@@ -396,7 +396,7 @@ sh.removeTagRange = function( ns, min, max, tag ) {
// behavior.
config.tags.remove( { _id : { ns : ns , min : min } , max : max , tag : tag } );
sh._checkLastError( config );
-}
+};
sh.getBalancerLockDetails = function(configDB) {
if (configDB === undefined)
@@ -409,7 +409,7 @@ sh.getBalancerLockDetails = function(configDB) {
return null;
}
return lock;
-}
+};
sh.getBalancerWindow = function(configDB) {
if (configDB === undefined)
@@ -421,26 +421,26 @@ sh.getBalancerWindow = function(configDB) {
if (settings.hasOwnProperty("activeWindow")){
return settings.activeWindow;
}
- return null
-}
+ return null;
+};
sh.getActiveMigrations = function(configDB) {
if (configDB === undefined)
configDB = db.getSiblingDB('config');
var activeLocks = configDB.locks.find( { _id : { $ne : "balancer" }, state: {$eq:2} });
- var result = []
+ var result = [];
if( activeLocks != null ){
activeLocks.forEach( function(lock){
result.push({_id:lock._id, when:lock.when});
- })
+ });
}
return result;
-}
+};
sh.getRecentFailedRounds = function(configDB) {
if (configDB === undefined)
configDB = db.getSiblingDB('config');
- var balErrs = configDB.actionlog.find({what:"balancer.round"}).sort({time:-1}).limit(5)
+ var balErrs = configDB.actionlog.find({what:"balancer.round"}).sort({time:-1}).limit(5);
var result = { count : 0, lastErr : "", lastTime : " "};
if(balErrs != null) {
balErrs.forEach( function(r){
@@ -449,10 +449,10 @@ sh.getRecentFailedRounds = function(configDB) {
result.lastErr = r.details.errmsg;
result.lastTime = r.time;
}
- })
+ });
}
return result;
-}
+};
/**
* Returns a summary of chunk migrations that was completed either successfully or not
@@ -529,7 +529,7 @@ function printShardingStatus(configDB, verbose) {
// configDB is a DB object that contains the sharding metadata of interest.
// Defaults to the db named "config" on the current connection.
if (configDB === undefined)
- configDB = db.getSisterDB('config')
+ configDB = db.getSisterDB('config');
var version = configDB.getCollection( "version" ).findOne();
if ( version == null ){
@@ -540,7 +540,7 @@ function printShardingStatus(configDB, verbose) {
var raw = "";
var output = function(s){
raw += s + "\n";
- }
+ };
output( "--- Sharding Status --- " );
output( " sharding version: " + tojson( configDB.getCollection( "version" ).findOne() ) );
@@ -608,20 +608,20 @@ function printShardingStatus(configDB, verbose) {
output( "\tCurrently running: " + ( sh.isBalancerRunning(configDB) ? "yes" : "no" ) );
//Output details of the current balancer round
- var balLock = sh.getBalancerLockDetails(configDB)
+ var balLock = sh.getBalancerLockDetails(configDB);
if ( balLock ) {
output( "\t\tBalancer lock taken at " + balLock.when + " by " + balLock.who );
}
//Output the balancer window
- var balSettings = sh.getBalancerWindow(configDB)
+ var balSettings = sh.getBalancerWindow(configDB);
if ( balSettings ) {
output( "\t\tBalancer active window is set between " +
balSettings.start + " and " + balSettings.stop + " server local time");
}
//Output the list of active migrations
- var activeMigrations = sh.getActiveMigrations(configDB)
+ var activeMigrations = sh.getActiveMigrations(configDB);
if (activeMigrations.length > 0 ){
output("\tCollections with active migrations: ");
activeMigrations.forEach( function(migration){
@@ -631,12 +631,12 @@ function printShardingStatus(configDB, verbose) {
// Actionlog and version checking only works on 2.7 and greater
var versionHasActionlog = false;
- var metaDataVersion = configDB.getCollection("version").findOne().currentVersion
+ var metaDataVersion = configDB.getCollection("version").findOne().currentVersion;
if ( metaDataVersion > 5 ) {
versionHasActionlog = true;
}
if ( metaDataVersion == 5 ) {
- var verArray = db.serverBuildInfo().versionArray
+ var verArray = db.serverBuildInfo().versionArray;
if (verArray[0] == 2 && verArray[1] > 6){
versionHasActionlog = true;
}
@@ -646,23 +646,23 @@ function printShardingStatus(configDB, verbose) {
//Review config.actionlog for errors
var actionReport = sh.getRecentFailedRounds(configDB);
//Always print the number of failed rounds
- output( "\tFailed balancer rounds in last 5 attempts: " + actionReport.count )
+ output( "\tFailed balancer rounds in last 5 attempts: " + actionReport.count );
//Only print the errors if there are any
if ( actionReport.count > 0 ){
- output( "\tLast reported error: " + actionReport.lastErr )
- output( "\tTime of Reported error: " + actionReport.lastTime )
+ output( "\tLast reported error: " + actionReport.lastErr );
+ output( "\tTime of Reported error: " + actionReport.lastTime );
}
output("\tMigration Results for the last 24 hours: ");
- var migrations = sh.getRecentMigrations(configDB)
+ var migrations = sh.getRecentMigrations(configDB);
if(migrations.length > 0) {
migrations.forEach( function(x) {
if (x._id === "Success"){
- output( "\t\t" + x.count + " : " + x._id)
+ output( "\t\t" + x.count + " : " + x._id);
} else {
output( "\t\t" + x.count + " : Failed with error '" + x._id
- + "', from " + x.from + " to " + x.to )
+ + "', from " + x.from + " to " + x.to );
}
});
} else {
@@ -675,7 +675,7 @@ function printShardingStatus(configDB, verbose) {
function(db){
var truthy = function (value) {
return !!value;
- }
+ };
var nonBooleanNote = function (name, value) {
// If the given value is not a boolean, return a string of the
// form " (<name>: <value>)", where <value> is converted to JSON.
@@ -685,7 +685,7 @@ function printShardingStatus(configDB, verbose) {
s = " (" + name + ": " + tojson(value) + ")";
}
return s;
- }
+ };
output( "\t" + tojsononeline(db,"",true) );
@@ -713,7 +713,7 @@ function printShardingStatus(configDB, verbose) {
res.forEach( function(z){
totalChunks += z.nChunks;
output( "\t\t\t\t" + z.shard + "\t" + z.nChunks );
- } )
+ } );
if ( totalChunks < 20 || verbose ){
configDB.chunks.find( { "ns" : coll._id } ).sort( { min : 1 } ).forEach(
@@ -732,10 +732,10 @@ function printShardingStatus(configDB, verbose) {
function( tag ) {
output( "\t\t\t tag: " + tag.tag + " " + tojson( tag.min ) + " -->> " + tojson( tag.max ) );
}
- )
+ );
}
}
- )
+ );
}
}
);
@@ -747,7 +747,7 @@ function printShardingSizes(configDB) {
// configDB is a DB object that contains the sharding metadata of interest.
// Defaults to the db named "config" on the current connection.
if (configDB === undefined)
- configDB = db.getSisterDB('config')
+ configDB = db.getSisterDB('config');
var version = configDB.getCollection( "version" ).findOne();
if ( version == null ){
@@ -758,7 +758,7 @@ function printShardingSizes(configDB) {
var raw = "";
var output = function(s){
raw += s + "\n";
- }
+ };
output( "--- Sharding Status --- " );
output( " sharding version: " + tojson( configDB.getCollection( "version" ).findOne() ) );
@@ -784,7 +784,7 @@ function printShardingSizes(configDB) {
output("\t\t" + coll._id + " chunks:");
configDB.chunks.find( { "ns" : coll._id } ).sort( { min : 1 } ).forEach(
function(chunk){
- var mydb = shards[chunk.shard].getDB(db._id)
+ var mydb = shards[chunk.shard].getDB(db._id);
var out = mydb.runCommand({dataSize: coll._id,
keyPattern: coll.key,
min: chunk.min,
@@ -798,10 +798,10 @@ function printShardingSizes(configDB) {
}
);
}
- )
+ );
}
}
);
print( raw );
-};
+}