Mongo Cheat Sheet


Command Notes
help show all the console commands (same as this section)
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
use set current database to help on DB methods help on collection methods list objects in collection foo{a:1}) list objects in foo where a == 1
it result of last line evaluated; use to further iterate


Command Notes
db.addUser(username, password)  
db.auth(username, password)  
db.commandHelp(name) returns the help for the command
db.copyDatabase(fromdb, todb, fromhost)  
db.createCollection(name, { size : …, capped : …, max : … } )  
db.currentOp() displays the current operation in the db
db.eval(func, args) run code server-side
db.getCollection(cname) same as db[‘cname’] or db.cname
db.getLastError() just returns the err msg string
db.getLastErrorObj() return full status object
db.getMongo() get the server connection object
db.getMongo().setSlaveOk() allow this connection to read from the nonmaster member of a replica pair
db.getSisterDB(name) get the db at the same server as this one
db.killOp() kills the current operation in the db
db.repairDatabase() Repair a database and compact to re-cliam unused space. This is SLOW and requires equal disk space to that used by the dataase already.
db.runCommand(cmdObj) run a database command. if cmdObj is a string, turns it into {cmdObj:1}
db.setProfilingLevel(level) 0=off 1=slow 2=all
db.version() current version of the server


Command Notes                                key ) eg. ‘x’ )          Drop the collection and all indexes. Use remove() to delete data.                               ,options) options should be an object with these possible fields: name, unique, dropDups          [query] , [fields]) first parameter is an optional query filter. second parameter is optional set of fields to return. e.g. { x : 77 } , { name : 1, x : 1 } )         …).count()           …).limit(n)           …).skip(n)           …).skip(n)           …).sort(…)           [query])            get DB object associated with collection                     { key : …, initial: …, reduce : …[, cond: …] } )            mapFunction , reduceFunction , )            deleted records from a collection leaving all indexes. Use drop() to delete the collection completely newName ) renames the collection includes free space allocated to this collection size in bytes of all the indexes storage allocated for all data and indexes, object[, upsert_bool, multi_record_bool]) SLOW only for use with sharding


Command Notes
mongodump -d database_name -o /some/directory  
mongorestore -d database_name /some/directory  


Example Command Notes
Inserting Data > j = { name: “mongo”};{“name” : “mongo”}  

t = { x : 3 };
{ “x” : 3 };; | Accessing Data from a Query | var cursor = db.things.find();
while (cursor.hasNext()) { print(tojson(; } | Retrieving Data with Javascript functions | db.things.find().forEach( function(x) { printjson(x);}); | select from things where name=”mongo” __ | db.things.find({name:”mongo”}).forEach(printjson); | select from things where x=4 | db.things.find({x:4}).forEach(printjson); | select j from things where x=4 | db.things.find({x:4}, {j:true}).forEach(printjson); | order by | db.things.find().sort({x:1}) // ascending
db.things.find().sort({x:-1}) // descending | limit 1 | var mongo = db.things.findOne({name:”mongo”});
print(tojson(mongo)); | limit(x) | db.things.find().limit(3); | regex search | db.things.find({x : /foo.*/i}); | search for type | db.things.find({ x : { $type : 16 }}); | finds integer values in this fields update users set api_token = ‘snafu’ where _id = “fubar”; | db.users.update( { “_id” : “fubar” }, { $set : { “api_token” : “snafu” } }, false ); | update or insert users set api_token = ‘snafu’ where _id = “fubar”; | update or insert users set api_token = ‘snafu’ where _id = “fubar”; | Rename all fields in a collection | db.users.update( {}, { $rename : {“old_field_name” : “new_field_name”}}, false, true); |


In addition to the general “help” command in mongo, you can call help on db and db.whatever to see a summary of methods available. MongoDB Manual:

Leave a comment

Your email address will not be published. Required fields are marked *