Mastering MongoDB Shell Commands: A Comprehensive Guide

Learn how to effectively interact with your MongoDB database using the powerful MongoDB Shell. This comprehensive guide will cover essential commands for connecting, configuring, querying, and managing your database. Discover the benefits of using the MongoDB Shell and enhance your MongoDB development skills.



MongoDB Shell Commands

The MongoDB Shell is a command-line client for interacting with your MongoDB database. It allows you to connect, configure, query, and work with your database.

Starting MongoDB Shell

Start the MongoDB Shell using the mongo or mongosh command. The mongosh shell has more features than the old mongo shell.

mongosh --help

This command displays all available options for mongosh:

C:\>mongosh --help

$ mongosh [options] [db address] [file names (ending in .js or .mongodb)]

Options:

-h, --help                                 Show usage information
-f, --file [arg]                           Load the specified script
    --host [arg]                           Server to connect to
    --port [arg]                           Port to connect to
    --version                              Show version info
    --verbose                              Increase output verbosity
    --quiet                                Silence output during connection
    --shell                                Run the shell after executing files
    --nodb                                 Don't connect to a database
    --norc                                 Skip loading '.mongoshrc.js'
    --eval [arg]                           Evaluate JavaScript
    --retryWrites                          Retry write operations on network errors

Authentication Options:
-u, --username [arg]                       Username for authentication
-p, --password [arg]                       Password for authentication
    --authenticationDatabase [arg]         Database for authentication
    --authenticationMechanism [arg]        Authentication mechanism
    --awsIamSessionToken [arg]             AWS IAM Temporary Session Token
    --gssapiServiceName [arg]              GSSAPI/Kerberos service name
    --sspiHostnameCanonicalization [arg]   SSPI hostname canonicalization
    --sspiRealmOverride [arg]              SSPI server realm

TLS Options:
    --tls                                  Use TLS for connections
    --tlsCertificateKeyFile [arg]          PEM certificate/key file for TLS
    --tlsCertificateKeyFilePassword [arg]  Password for key in PEM file
    --tlsCAFile [arg]                      CA file for TLS
    --tlsAllowInvalidHostnames             Allow connections to servers with non-matching hostnames
    --tlsAllowInvalidCertificates          Allow connections with invalid certificates
    --tlsCertificateSelector [arg]         TLS Certificate in system store
    --tlsCRLFile [arg]                     CRL file for TLS
    --tlsDisabledProtocols [arg]           Comma separated list of TLS protocols to disable

API Version Options:
    --apiVersion [arg]                     Specifies API version
    --apiStrict                            Use strict API version mode
    --apiDeprecationErrors                 Fail deprecated commands

FLE Options:
    --awsAccessKeyId [arg]                 AWS Access Key for FLE Amazon KMS
    --awsSecretAccessKey [arg]             AWS Secret Key for FLE Amazon KMS
    --awsSessionToken [arg]                Optional AWS Session Token
    --keyVaultNamespace [arg]              Database.collection for encrypted FLE parameters
    --kmsURL [arg]                         KMS endpoint URL

DB Address Examples:
    foo                                    Foo database on local machine
    192.168.0.5/foo                        Foo database on 192.168.0.5
    192.168.0.5:9999/foo                   Foo database on port 9999
    mongodb://192.168.0.5:9999/foo         Connection string URI

File Names:
    List of files to run (ending in .js)

Example:
    Start mongosh using 'ships' database:
    $ mongosh mongodb://192.168.0.5:9999/ships

For more info: https://docs.mongodb.com/mongodb-shell

Connecting to MongoDB Database

By default, mongosh connects to the local MongoDB database at localhost:27017. To connect to a different port, use the --port option:

C:\>mongosh --port 23023

To connect to a remote database, use the connection string URI:

C:\>mongosh "mongodb://mymongodb.example.com:23023"

Alternatively, use --host and --port options:

C:\>mongosh --host mongodb0.example.com --port 28015

For authentication, use --username and --authenticationDatabase options:

C:\>mongosh "mongodb://mymongodb.example.com:23023" --username steve --authenticationDatabase admin

MongoDB Command Help

After connecting to a database, use the help command for a list of available commands:

test> help
use                                        Set current database
show                                       List databases, collections, users, and roles
exit                                       Quit the shell
quit                                       Quit the shell
Mongo                                      Create a new connection
connect                                    Create a new connection and return the Database object
it                                         Result of the last line evaluated
version                                    Shell version
load                                       Load and run a JavaScript file
enableTelemetry                            Enable anonymous usage data collection
disableTelemetry                           Disable anonymous usage data collection
passwordPrompt                             Prompt for a password
sleep                                      Sleep for specified milliseconds
print                                      Print object contents
printjson                                  Print object contents as JSON
cls                                        Clear the screen
isInteractive                              Check if the shell is in interactive mode

Command: show.help

'show databases'/'show dbs': Print a list of all available databases.
'show collections'/'show tables': Print a list of all collections for current database.
'show profile': Prints system.profile information.
'show users': Print a list of all users for current database.
'show roles': Print a list of all roles for current database.
'show log ': log for current connection, if type is not set uses 'global'
'show logs': Print all logs.
        

Command: show dbs

admin              41 kB
config           73.7 kB
humanresourcedb    41 kB
local            73.7 kB
        

Command: show collections

Lists collections in the current database 'admin'.
system.version
        

Command: db.help()

Database Class:

getMongo                                   Returns the current database connection
getName                                    Returns the name of the DB
getCollectionNames                         Returns an array containing the names of all collections in the current database.
getCollectionInfos                         Returns an array of documents with collection information, i.e. collection name and options, for the current database.
runCommand                                 Runs an arbitrary command on the database.
adminCommand                               Runs an arbitrary command against the admin database.
aggregate                                  Runs a specified admin/diagnostic pipeline which does not require an underlying collection.
getSiblingDB                               Returns another database without modifying the db variable in the shell environment.
getCollection                              Returns a collection or a view object that is functionally equivalent to using the db.
dropDatabase                               Removes the current database, deleting the associated data files.
createUser                                 Creates a new user for the database on which the method is run.
updateUser                                 Updates the user's profile on the database on which you run the method.
changeUserPassword                         Updates a user's password.
logout                                     Ends the current authentication session.
dropUser                                   Removes the user from the current database.
dropAllUsers                               Removes all users from the current database.
auth                                       Allows a user to authenticate to the database from within the shell.
grantRolesToUser                           Grants additional roles to a user.
revokeRolesFromUser                        Removes roles from a user on the current database.
getUser                                    Returns user information for a specified user.
getUsers                                   Returns information for all users in the database.
createCollection                           Create new collection
createView                                 Create new view
createRole                                 Creates a new role.
updateRole                                 Updates the role's profile on the database.
dropRole                                   Removes the role from the current database.
dropAllRoles                               Removes all roles from the current database.
grantRolesToRole                           Grants additional roles to a role.
revokeRolesFromRole                        Removes roles from a role on the current database.
grantPrivilegesToRole                      Grants additional privileges to a role.
revokePrivilegesFromRole                   Removes privileges from a role on the current database.
getRole                                    Returns role information for a specified role.
getRoles                                   Returns information for all roles in the database.
currentOp                                  Calls the currentOp command.
killOp                                     Calls the killOp command.
shutdownServer                             Calls the shutdown command.
fsyncLock                                  Calls the fsync command.
fsyncUnlock                                Calls the fsyncUnlock command.
version                                    returns the db version.
serverBits                                 returns the db serverBits.
isMaster                                   Calls the isMaster command
hello                                      Calls the hello command
serverBuildInfo                            returns the db serverBuildInfo.
serverStatus                               returns the server stats.
stats                                      returns the db stats.
hostInfo                                   Calls the hostInfo command
serverCmdLineOpts                          returns the db serverCmdLineOpts.
rotateCertificates                         Calls the rotateCertificates command
printCollectionStats                       Prints the collection.stats for each collection in the db.
getFreeMonitoringStatus                    Calls the getFreeMonitoringStatus command
disableFreeMonitoring                      returns the db disableFreeMonitoring.
enableFreeMonitoring                       returns the db enableFreeMonitoring.
getProfilingStatus                         returns the db getProfilingStatus.
setProfilingLevel                          returns the db setProfilingLevel.
setLogLevel                                returns the db setLogLevel.
getLogComponents                           returns the db getLogComponents.
cloneDatabase                              deprecated, non-functional
cloneCollection                            deprecated, non-functional
copyDatabase                               deprecated, non-functional
commandHelp                                returns the db commandHelp.
listCommands                               Calls the listCommands command
getLastErrorObj                            Calls the getLastError command
getLastError                               Calls the getLastError command
printShardingStatus                        Calls sh.status(verbose)
printSecondaryReplicationInfo              Prints secondary replicaset information
getReplicationInfo                         Returns replication information
printReplicationInfo                       Formats sh.getReplicationInfo
printSlaveReplicationInfo                  DEPRECATED. Use db.printSecondaryReplicationInfo
setSecondaryOk                             This method is deprecated.
watch                                      Opens a change stream cursor on the database
        

Command: db.test.help()

Collection Class:
aggregate                                  Calculates aggregate values for the data in a collection or a view.
bulkWrite                                  Performs multiple write operations with controls for order of execution.
count                                      Returns the count of documents that would match a find() query for the collection or view.
countDocuments                             Returns the count of documents that match the query for a collection or view.
deleteMany                                 Removes all documents that match the filter from a collection.
deleteOne                                  Removes a single document from a collection.
distinct                                   Finds the distinct values for a specified field across a single collection or view and returns the results in an array.
estimatedDocumentCount                     Returns the count of all documents in a collection or view.
find                                       Selects documents in a collection or view.
findAndModify                              Modifies and returns a single document.
findOne                                    Selects documents in a collection or view.
renameCollection                           Renames a collection.
findOneAndDelete                           Deletes a single document based on the filter and sort criteria, returning the deleted document.
findOneAndReplace                          Modifies and replaces a single document based on the filter and sort criteria.
findOneAndUpdate                           Updates a single document based on the filter and sort criteria.
insert                                     Inserts a document or documents into a collection.
insertMany                                 Inserts multiple documents into a collection.
insertOne                                  Inserts a document into a collection.
isCapped                                   Checks if a collection is capped
remove                                     Removes documents from a collection.
save                                       Updates an existing document or inserts a new document, depending on its document parameter.
replaceOne                                 Replaces a single document within the collection based on the filter.
update                                     Modifies an existing document or documents in a collection.
updateMany                                 Updates all documents that match the specified filter for a collection.
updateOne                                  Updates a single document within the collection based on the filter.
convertToCapped                            calls {convertToCapped:'coll', size:maxBytes}} command
createIndexes                              Creates one or more indexes on a collection
createIndex                                Creates one index on a collection
ensureIndex                                Creates one index on a collection
getIndexes                                 Returns an array that holds a list of documents that identify and describe the existing indexes on the collection.
getIndexSpecs                              Alias for getIndexes. Returns an array that holds a list of documents that identify and describe the existing indexes on the collection.
getIndices                                 Alias for getIndexes. Returns an array that holds a list of documents that identify and describe the existing indexes on the collection.
getIndexKeys                               Return an array of key patterns for indexes defined on collection
dropIndexes                                Drops the specified index or indexes (except the index on the _id field) from a collection.
dropIndex                                  Drops or removes the specified index from a collection.
totalIndexSize                             Reports the total size used by the indexes on a collection.
reIndex                                    Rebuilds all existing indexes on a collection.
getDB                                      Get current database.
getMongo                                   Returns the Mongo object.
dataSize                                   This method provides a wrapper around the size output of the collStats (i.e. db.collection.stats()) command.
storageSize                                The total amount of storage allocated to this collection for document storage.
totalSize                                  The total size in bytes of the data in the collection plus the size of every index on the collection.
drop                                       Removes a collection or view from the database.
exists                                     Returns collection infos if the collection exists or null otherwise.
getFullName                                Returns the name of the collection prefixed with the database name.
getName                                    Returns the name of the collection.
runCommand                                 Runs a db command with the given name where the first param is the collection name.
explain                                    Returns information on the query plan.
stats                                      Returns statistics about the collection.
latencyStats                               returns the $latencyStats aggregation for the collection. Takes an options document with an optional boolean 'histograms' field.
initializeOrderedBulkOp                    Initializes an ordered bulk command. Returns an instance of Bulk
initializeUnorderedBulkOp                  Initializes an unordered bulk command. Returns an instance of Bulk
getPlanCache                               Returns an interface to access the query plan cache for a collection. The interface provides methods to view and clear the query plan cache.
mapReduce                                  Calls the mapReduce command
validate                                   Calls the validate command. Default full value is false
getShardVersion                            Calls the getShardVersion command
getShardDistribution                       Prints the data distribution statistics for a sharded collection.
watch                                      Opens a change stream cursor on the collection
hideIndex                                  Hides an existing index from the query planner.
unhideIndex                                Unhides an existing index from the query planner.
    

For more information on MongoDB commands, visit: MongoDB Command Reference