The mongo Shell
The mongo shell is an interactive JavaScript interface to MongoDB. You can use the mongo shell to query and update data as well as perform administrative operations.
mongo Shell Quick Reference
Access the mongo Shell Help
To see the list of options and help for starting the mongo shell, use the --help option from the command line:
mongo --help
Start the mongo Shell
mongo --host 127.0.0.1:27017
>
Shell Help
To see the list of help, in the mongo shell, type help:
help
db.help() help on db methods
db.mycoll.help() help on collection methods
sh.help() sharding helpers
rs.help() replica set helpers
help admin administrative help
help connect connecting to a db help
help keys key shortcuts
help misc misc things to know
help mr mapreduce
show dbs show database names
show collections show collections in current database
show users show users in current database
show profile show most recent system.profile entries with time >= 1ms
show logs show the accessible logger names
show log [name] prints out the last segment of log in memory, 'global' is default
use <db_name> set current database
db.foo.find() list objects in collection foo
db.foo.find( { a : 1 } ) list objects in foo where a == 1
it result of the last line evaluated; use to further iterate
DBQuery.shellBatchSize = x set default number of items to display on shell
exit quit the mongo shell
Database Help
To see the list of databases on the server, use the show dbs command:
show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
myNewDB 0.000GB
myNewDatabase 0.000GB
test 0.000GB
To see the list of help for methods you can use on the db object, call the db.help() method:
db.help()
DB methods:
db.adminCommand(nameOrDocument) - switches to 'admin' db, and runs command [just calls db.runCommand(...)]
db.aggregate([pipeline], {options}) - performs a collectionless aggregation on this database; returns a cursor
db.auth(username, password)
db.cloneDatabase(fromhost) - deprecated
db.commandHelp(name) returns the help for the command
...
To see the implementation of a method in the shell, type the db.<method name> without the parenthesis (())
db.updateUser
function (name, updateObject, writeConcern) {
var cmdObj = {updateUser: name};
cmdObj = Object.extend(cmdObj, updateObject);
cmdObj['writeConcern'] = writeConcern ? writeConcern : _defaultWriteConcern;
this._modifyCommandToDigestPasswordIfNecessary(cmdObj, name);
var res = this.runCommand(cmdObj);
if (res.ok) {
return;
}
if (res.errmsg == "no such cmd: updateUser") {
this._updateUserV1(name, updateObject, cmdObj['writeConcern']);
return;
}
throw _getErrorWithCode(res, "Updating user failed: " + res.errmsg);
}
Collection Help
To see the list of collections in the current database, use the show collections command:
show collections
inventory
To see the help for methods available on the collection objects
db.collection.help()
DBCollection help
db.collection.find().help() - show DBCursor help
db.collection.bulkWrite( operations, <optional params> ) - bulk execute write operations, optional parameters are: w, wtimeout, j
db.collection.count( query = {}, <optional params> ) - count the number of documents that matches the query, optional parameters are: limit, skip, hint, maxTimeMS
db.collection.copyTo(newColl) - duplicates collection by copying all documents to newColl; no indexes are copied.
...
To see the collection method implementation, type the db.<collection>.<method> name without the parenthesis (())
db.collection.save
function (obj, opts) {
if (obj == null)
throw Error("can't save a null");
if (typeof(obj) == "number" || typeof(obj) == "string")
throw Error("can't save a number or string");
if (typeof(obj._id) == "undefined") {
obj._id = new ObjectId();
return this.insert(obj, opts);
} else {
return this.update({_id: obj._id}, obj, Object.merge({upsert: true}, opts));
}
}
Cursor Help
When you perform read operations with the find() method in the mongo shell, you can use various cursor methods to modify the find() behavior and various JavaScript methods to handle the cursor returned from the find() method.
To list the available modifier and cursor handling methods, use the db.collection.find().help() command:
db.collection.find().help()
find(<predicate>, <projection>) modifiers
.sort({...})
.limit(<n>)
.skip(<n>)
.batchSize(<n>) - sets the number of docs to return per getMore
.collation({...})
...
To see the implementation of the cursor method, type the db.<collection>.find().<method> name without the parenthesis (())
db.collection.find().toArray
function () {
if (this._arr)
return this._arr;
var a = [];
while (this.hasNext())
a.push(this.next());
this._arr = a;
return a;
}
Wrapper Object Help
To get a list of the wrapper classes available in the mongo shell, such as BinData(), type help misc in the mongo shell:
help misc
b = new BinData(subtype,base64str) create a BSON BinData value
b.subtype() the BinData subtype (0..255)
b.length() length of the BinData data in bytes
b.hex() the data as a hex encoded string
b.base64() the data as a base 64 encoded string
b.toString()
b = HexData(subtype,hexstr) create a BSON BinData value from a hex string
b = UUID(hexstr) create a BSON BinData value of UUID subtype
b = MD5(hexstr) create a BSON BinData value of MD5 subtype
"hexstr" string, sequence of hex characters (no 0x prefix)
o = new ObjectId() create a new ObjectId
o.getTimestamp() return timestamp derived from first 32 bits of the OID
o.isObjectId
o.toString()
o.equals(otherid)
d = ISODate() like Date() but behaves more intuitively when used
d = ISODate('YYYY-MM-DD hh:mm:ss') without an explicit "new " prefix on construction
Exit the Shell
To exit the shell, type quit() or use the <Ctrl-C> shortcut.