MongoDB Shell Commands

MongoDB Shell is the quickest way to connect, configure, query, and work with your MongoDB database. It acts as a command-line client of the MongoDB server.

You can start MongoDB Shell by executing mongo or mongosh command on the command prompt/terminal. mongosh is the new MongoDB shell with some more features than the old mongo shell.

mongosh <commands>

The --help command display all the commands which you can use with mongo or mongosh, as shown below.

C:\>mongosh --help

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

  Options:

    -h, --help                                 Show this usage information
    -f, --file [arg]                           Load the specified mongosh script
        --host [arg]                           Server to connect to
        --port [arg]                           Port to connect to
        --version                              Show version information
        --verbose                              Increase the verbosity of the output of the shell
        --quiet                                Silence output from the shell during the connection process
        --shell                                Run the shell after executing files
        --nodb                                 Don't connect to mongod on startup - no 'db address' [arg] expected
        --norc                                 Will not run the '.mongoshrc.js' file on start up
        --eval [arg]                           Evaluate javascript
        --retryWrites                          Automatically retry write operations upon transient network errors

  Authentication Options:

    -u, --username [arg]                       Username for authentication
    -p, --password [arg]                       Password for authentication
        --authenticationDatabase [arg]         User source (defaults to dbname)
        --authenticationMechanism [arg]        Authentication mechanism
        --awsIamSessionToken [arg]             AWS IAM Temporary Session Token ID
        --gssapiServiceName [arg]              Service name to use when authenticating using GSSAPI/Kerberos
        --sspiHostnameCanonicalization [arg]   Specify the SSPI hostname canonicalization (none or forward, available on Windows)
        --sspiRealmOverride [arg]              Specify the SSPI server realm (available on Windows)

  TLS Options:

        --tls                                  Use TLS for all connections
        --tlsCertificateKeyFile [arg]          PEM certificate/key file for TLS
        --tlsCertificateKeyFilePassword [arg]  Password for key in PEM file for TLS
        --tlsCAFile [arg]                      Certificate Authority file for TLS
        --tlsAllowInvalidHostnames             Allow connections to servers with non-matching hostnames
        --tlsAllowInvalidCertificates          Allow connections to servers with invalid certificates
        --tlsCertificateSelector [arg]         TLS Certificate in system store (Windows and macOS only)
        --tlsCRLFile [arg]                     Specifies the .pem file that contains the Certificate Revocation List
        --tlsDisabledProtocols [arg]           Comma separated list of TLS protocols to disable [TLS1_0,TLS1_1,TLS1_2]

  API version options:

        --apiVersion [arg]                     Specifies the API version to connect with
        --apiStrict                            Use strict API version mode
        --apiDeprecationErrors                 Fail deprecated commands for the specified API version

  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 ID
        --keyVaultNamespace [arg]              database.collection to store encrypted FLE parameters
        --kmsURL [arg]                         Test parameter to override the URL of the KMS endpoint

  DB Address Examples:

        foo                                    Foo database on local machine
        192.168.0.5/foo                        Foo database on 192.168.0.5 machine
        192.168.0.5:9999/foo                   Foo database on 192.168.0.5 machine on port 9999
        mongodb://192.168.0.5:9999/foo         Connection string URI can also be used

  File Names:

        A list of files to run. Files must end in .js and will exit after unless --shell is specified.

  Examples:

        Start mongosh using 'ships' database on specified connection string:
        $ mongosh mongodb://192.168.0.5:9999/ships

  For more information on usage: https://docs.mongodb.com/mongodb-shell.

For example, the --nodb allows you to run MongoDB shell without connecting to a database.

C:\>mongosh --nodb
Current Mongosh Log ID: 6166bab1a1acde9f7f388c27
Using Mongosh:          1.1.0

For mongosh info see: https://docs.mongodb.com/mongodb-shell/

Warning: Found ~/.mongorc.js, but not ~/.mongoshrc.js. ~/.mongorc.js will not be loaded.
  You may want to copy or rename ~/.mongorc.js to ~/.mongoshrc.js.
>

Connect to MongoDB Database

By default, the mongosh or mongo command connects with the local MongoDB database on the localhost:27017. So, mongosh and mongosh "mongodb://localhost:27017" are the same that connect to a database on the localhost at port 27017.

To connect with the local database on a different port, use the --port option:

C:\>mongosh --port 23023

The following connects to the remote database on mymongodb.example.com at port 23023.

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

Or, use the --host and --port options:

mongosh --host mongodb0.example.com --port 28015

Use the --username and --authenticationDatabase command-line options to connect with the database that requires authentication.

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

Learn more about connect to mongodb options.

MongoDB Command Help

You can also get help on mongosh or mongo commands after connecting to a database using the help command, as shown below.

test> help
Using MongoDB:          5.0.3
  Shell Help::          1.1.0

    use                                        Set current database
    show                                       'show databases'/'show dbs': Print a list of all available databases.
                                               'show collections'/'show tables': Print a list of all collections for current database.generated these startup warnings when booting:
                                               'show profile': Prints system.profile information.access to data and conf
                                               '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.

    exit                                       Quit the MongoDB shell with exit/exit()/.exit
    quit                                       Quit the MongoDB shell with quit/quit()
    Mongo                                      Create a new connection and return the Mongo object. Usage: new Mongo(URI, options [optional])
    connect                                    Create a new connection and return the Database object. Usage: connect(URI, username [optional], password [optional])
    it                                         result of the last line evaluated; use to further iterate
    version                                    Shell version
    load                                       Loads and runs a JavaScript file into the current shell environment
    enableTelemetry                            Enables collection of anonymous usage data to improve the mongosh CLI
    disableTelemetry                           Disables collection of anonymous usage data to improve the mongosh CLI
    passwordPrompt                             Prompts the user for a password
    sleep                                      Sleep for the specified number of milliseconds
    print                                      Prints the contents of an object to the output
    printjson                                  Alias for print()
    cls                                        Clears the screen like console.clear()
    isInteractive                              Returns whether the shell will enter or has entered interactive mode

  For more information on usage: https://docs.mongodb.com/manual/reference/method
test>
    

As you can see above, use various commands to work with the connected database. Append .help on the above command to get the help of that command. For example, execute the show.help command to display the help of the show, as shown below.

test> 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.
    

The show dbs command will display all the databases on the connected server.

test> show dbs
admin              41 kB
config           73.7 kB
humanresourcedb    41 kB
local            73.7 kB

The show collections commands shows collections in current database admin.

admin> show collections
system.version

Use the db.help() command to get the help on db command.

test> 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. db.createUser() returns a duplicate user error if the user already exists on the database.
    updateUser                                 Updates the user's profile on the database on which you run the method. An update to a field completely replaces the previous field's values. This includes updates to the user's roles array.
    changeUserPassword                         Updates a user's password. Run the method in the database where the user is defined, i.e. the database you created the user.
    logout                                     Ends the current authentication session. This function has no effect if the current session is not authenticated.
    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 a one or more roles from a user on the current database.
    getUser                                    Returns user information for a specified user. Run this method on the user's database. The user must exist on the database on which the method runs.
    getUsers                                   Returns information for all the 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 on which you run the method. An update to a field completely replaces the previous field's values.
    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 a one or more roles from a role on the current database.
    grantPrivilegesToRole                      Grants additional privileges to a role.
    revokePrivilegesFromRole                   Removes a one or more privileges from a role on the current database.
    getRole                                    Returns role information for a specified role. Run this method on the role's database. The role must exist on the database on which the method runs.
    getRoles                                   Returns information for all the roles in the database.
    currentOp                                  Calls the currentOp command. Returns a document that contains information on in-progress operations for the database instance. The db.currentOp() method wraps the database command currentOp.
    killOp                                     Calls the killOp command. Terminates an operation as specified by the operation ID. To find operations and their corresponding IDs, see $currentOp or db.currentOp().
    shutdownServer                             Calls the shutdown command. Shuts down the current mongod or mongos process cleanly and safely. You must issue the db.shutdownServer() operation against the admin database.
    fsyncLock                                  Calls the fsync command. Forces the mongod to flush all pending write operations to disk and locks the entire mongod instance to prevent additional writes until the user releases the lock with a corresponding db.fsyncUnlock() command.
    fsyncUnlock                                Calls the fsyncUnlock command. Reduces the lock taken by db.fsyncLock() on a mongod instance by 1.
    version                                    returns the db version. uses the buildinfo command
    serverBits                                 returns the db serverBits. uses the buildInfo command
    isMaster                                   Calls the isMaster command
    hello                                      Calls the hello command
    serverBuildInfo                            returns the db serverBuildInfo. uses the buildInfo command
    serverStatus                               returns the server stats. uses the serverStatus command
    stats                                      returns the db stats. uses the dbStats command
    hostInfo                                   Calls the hostInfo command
    serverCmdLineOpts                          returns the db serverCmdLineOpts. uses the getCmdLineOpts command
    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. uses the setFreeMonitoring command
    enableFreeMonitoring                       returns the db enableFreeMonitoring. uses the setFreeMonitoring command
    getProfilingStatus                         returns the db getProfilingStatus. uses the profile command
    setProfilingLevel                          returns the db setProfilingLevel. uses the profile command
    setLogLevel                                returns the db setLogLevel. uses the setParameter command
    getLogComponents                           returns the db getLogComponents. uses the getParameter command
    cloneDatabase                              deprecated, non-functional
    cloneCollection                            deprecated, non-functional
    copyDatabase                               deprecated, non-functional
    commandHelp                                returns the db commandHelp. uses the passed in command with help: true
    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. Use db.getMongo().setReadPref() instead
    watch                                      Opens a change stream cursor on the database

Use db.test.help() command to get the help on collection related commands.

test> 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.

Visit MongoDB shell commands for all the command options.

Want to check how much you know MongoDB?