Shell cheat sheet
for MongoDB version 3.4
Database Administration CRUD Queries Analytic Queries
Command line tools Query commands (db.collection.) Aggregation Operators ( $ )
mongo | Start the shell from the command line find()| perform a query and return a results cursor Pipeline Operators
command line options: findAndModify() | atomically find and update $project | reshape a document
--host hostname | hostname to connect to findOne() | perform a query and return a document $match | match documents against a query
--port 27017 | connect to port 27017 (default) distinct() | query for distinct documents on a field $limit | restrict the number of documents returned
-u foo | username foo insert() | insert a new document into the collection $skip | skip over some documents and return the rest
-p bar | password bar remove() | remove a document from a collection $unwind | open elements of an array into documents
--authenticationDatabase arg | database to authenticate to save() | wrapper around insert and update to save $group | group on a field and aggregate values
mongoimport | import data from a file to mongodb update() | update one or more documents $sort | sort on a specified field
mongodump | dump contents of a database to files $geoNear | get documents near a geospatial point
mongorestore | restore contents of a dump to a database
mongotop | profile the resources mongo is consuming Query Operators ( $ )
mongostat | profile the amount of time spent in collections
Comparison
Aggregation Expression Operators ($)
$gt | matches values greater than the value
$gte | matches values greater than or equal the value Accumulators ($group and $project stages)
Basic shell commands $addToSet | return a unique array of values for group
$in | matches values supplied in an array
$lt | matches values less than the value $first | return the first value in a group
help | get help for the context you're in $lte | matches values less than or equal the value $last | return the last value in a group
quit(), <ctrl+c> | exit the shell $ne | matches all values that are not equal to given $max | return the highest value in a group
db | show the selected database $nin | matches values that do not exist in an array $min | return the lowest value in a group
use foo | select and use the database foo $avg | return an average of all values in a group
Logical
show dbs | show databases on server $push | return an array of values for a grouped field
$or | joins query clauses with a logical OR
show collections | show collections in the current db $sum | return the sum of all values in a group
$and | joins query clauses with a logical AND
show users | show the users in the current db $stdDevPop | return the population standard deviation of the input
$not | returns documents that do not match
show roles | list all built in and user defined roles in the current db $stdDevSamp | return the sample standard deviation of the input
$nor | joins query clauses with a logical NOR
Boolean Operators
Element
$and | returns true when all values in array are true
$exists | matches documents that have a field
Collection commands (db.collection.) $type | matches a field if it is of a given type
$or | returns true when any value in its array are true
$not | returns boolean value that is opposite of input
Evaluation
help() | show a list of help commands for a collection Comparison Operators
$mod | perform a modulo on a field and select if 0
copyTo() | copy a collection to a new collection name $cmp | return the result of a compare as an integer
$regex | matches a regex expression on a field
count() | get number of documents in the collection $eq | return true if two values are equal
$where | matches against a JavaScript expression
drop() | remove the collection from the database $gt | return true if first value greater than 2nd
Geospatial $gte | return true if first value greater or equal to 2nd
mapReduce() | performs map-reduce data aggregate $geoWithin | matches within a bounding geometry
renameCollection() | rename a collection $lt | return true if first value less than 2nd
$geoIntersects | matches intersection in a geometry $lte | return true if first value less than or equal 2nd
stats() | get stats about the collection $near | matches near a geospatial point $ne | return true if two values are not equal
$nearSphere | matches near a point on a sphere
Arithmetic Operators
Array $add | return the sum of an array of numbers
Indexing $all | matches arrays that contain all elements given $divide | return the result of dividing two numbers
$elemMatch | matches multiple conditions in array $mod | return the modulo of dividing two numbers
dropIndex() | removes a specified index on a collection $size | matches if the array is of specified size $multiply | return the product of an array of numbers
createIndex() | creates an index if it does not currently exist $subtract | return the result of subtracting 2 numbers
getIndexes() | gets details on the indexes on a collection
Update Operators ( $ ) String Operators
reIndex() | rebuilds all existing indexes on a collection
$concat | concatenate two strings
compact | defragments a collection and rebuilds the indexes
$strcasecmp | return an int reflecting a comparison
Fields $substr | return a portion of a string
$inc | increment a value by a specified amount $toLower | convert a string to lowercase
Index options $rename | rename a field $toUpper | convert a string to uppercase
$setOnInsert |set a value only if inserting
$set | set the value of a field on an existing document Date Operators
Index Properties $unset | remove the field from an existing document $dayOfYear | return an int between 1 and 366
expireAfterSeconds | delete documents after set time $dayOfMonth | return an int between 1 and 31
unique | create indexes that allow only unique data Array Operators $dayOfWeek | return an int between 1 and 7
sparse | index only documents having the index field $ | update the first element in an array that matches $year | return the full year from a date
partial | index only documents meeting a filter criteria $addToSet | add element to array if it doesn't exist $month | return an int between 1 and 12
$pop | remove the first or last item of an array $week | return an int between 0 and 53
Index Creation Options $pullAll | remove multiple values from an array
background | create index in the background $hour | return an int between 0 and 23
$pull | remove items which match a query statement $minute | return an int between 0 and 59
$push | adds an item to an array $second | return an int between 0 and 60
Array Modifiers $millisecond | return millisecond portion of a date
Cursors (db.collection.find.) $each | modify $push and $addToSet to add many $dateToString | return the date as a formatted string
$slice | modify $push to limit size of updated array Conditional Expressions
iteration | iterate on a cursor using its variable reference $sort | modify $push to reorder documents in array $cond | ternary style operator, takes 3 expressions
count() | return a count of the documents in a cursor $position | modify $push to specify the location to push at in array $ifNull | eval 1st expression, if null eval 2nd, return
explain() | get the query execution plan for a cursor Bitwise
hasNext() | true if cursor has documents and can be iterated $bit | performs bitwise AND and OR updates
hint() | force db to use a specific index for a query Isolation
limit() | constrain the size of a cursor's result set $isolated | improve isolation of the operation
next() | return the next document in a cursor
skip() | skip through some documents and then return results
Misc links
sort() | return results ordered according to a sort specification Projection Operators ( $ )
toArray() | return an array of all documents for the cursor Release Notes
pretty() | pretty print the documents returned Backup and Recovery
$ | project the first element in an array that matches Manage Journaling
$elemMatch | project only the first element match MongoDB Scripting
$slice | limit number of elements projected from array Analyze Performance and Profiling
Security
Community
System Administration
DB commands (db.) Replication (rs.) Sharding (sh.)
help() | show a list of help commands for a db add() | adds a member to a replica set addShard() | add a shard to the cluster
copyDatabase() | copies a db to another db addArb() | adds an arbiter to a replica set addShardTag() | associate a shard with a tag
dropDatabase() | remove the current db conf() | returns the replica set config document addTagRange() | associate range of shard keys with tag
getLastError() | get status of last error freeze() | prevents a member from becoming primary disableBalancing() | disable balancing on a collection
hostInfo() | getinfo about the host system help() | get basic help for replica set functions enableBalancing() | re-enable balancing on a collection
serverStatus() | get an overview of server status initiate() | initializes a new replica set enableSharding() | enables sharding on a database
shutdownServer() | shutdown current server reconfig() | reconfigure a replica set with a new config getBalancerHost() | get the mongos doing balancing
stats() | get stats on the current db selected remove() | remove a member from a replica set getBalancerState() | true if the balancer is enabled
version() | get the current version of the server slaveOk() | allow reads to happen on a seconary help() | returns help text for the sh methods
status() | return a document with status of replica set isBalancerRunning | true if the balancer is migrating
stepDown() | force primary to step down moveChunk() | migrates a chunk in a sharded cluster
Authentication syncFrom() | specify the member to sync from removeShardTag() | disassociate a shard with a tag
Read Preferences setBalancerState() | enable or disable the balancer
primary | read only from the primary in a replica set shardCollection() | enables sharding for a collection
db.createUser() | create a user in the system.users collection splitAt() | divide a chunk in 2 based on shard key value
db.changeUserPassword() | change an existing users password primaryPreferred | prefer the primary but can read from secondary
secondary | read only from a secondary in a replica set splitFind() | divide a chunk in half based on a query
db.dropUser() | remove a user from a database startBalancer() | enable balancer and wait until started
secondaryPreferred | prefer a secondary, read from primary last
db.auth() | authenticates a user to a database nearest | read from the nearest member in a replica set status() | reports on the status of a sharded cluster
db.logout() | logout from a database stopBalancer() | stop balancer and wait until stopped
Created By: Daniel Hodgin @dhhodgin www.hodgin.ca Last updated: November 20, 2016