Connect to a Deployment (2024)

Docs Home

/

MongoDB Shell

On this page

  • Prerequisites
  • Supported MongoDB Versions
  • Install mongosh
  • Connect to a MongoDB Atlas Deployment
  • Get your Atlas Connection String
  • Set Your Database Credentials
  • Connect to MongoDB Atlas with mongosh
  • Connect to a Local Deployment on the Default Port
  • Connect to a Local Deployment on a Non-Default Port
  • Connect to a Deployment on a Remote Host
  • Specify Connection Options
  • Connect With Authentication
  • Connect with OpenID Connect
  • Connect with LDAP
  • Connect to a Replica Set
  • Connect Using TLS
  • Connect to a Specific Database
  • Proxy Settings
  • Connect to a Different Deployment
  • Verify Current Connection
  • Disconnect from a Deployment
  • Non-genuine Deployments
  • Limitations

This page shows how to use the MongoDB Shell to connect to a MongoDBdeployment. You can connect to aMongoDB Atlas cloud-hosted deployment,connect to a local deployment, or connect to another remote host withMongoDB Shell.

Prerequisites

To use the MongoDB Shell, you must have a MongoDB deployment to connectto.

  • For a free cloud-hosted deployment, you can useMongoDB Atlas.

  • To learn how to run a local MongoDB deployment, seeInstall MongoDB.

Supported MongoDB Versions

You can use the MongoDB Shell to connect to MongoDB version 4.2 orgreater.

Install mongosh

These procedures assume you have already installed mongosh. For moreinformation about installing mongosh, refer toInstall mongosh.

Connect to a MongoDB Atlas Deployment

You can connect to your MongoDB Atlas deployment directly from your shell.

1

Get your Atlas Connection String

You need an Atlas connection string to connect from MongoDB Shell.You can get the Atlas connection string in the Atlas UI.

Refer to theFind Your MongoDB Atlas Connection Stringguide for details.

2

Set Your Database Credentials

If you haven't alreadycreated a database user,you must set a username and password. To connect to Atlas, pass your username withthe Atlas connection string. After you issue the connect command, theshell prompts for your password.

3

Connect to MongoDB Atlas with mongosh

To establish your connection, run the mongosh command with yourconnection string and options to establish the connection.

The connection string includes the following elements:

  • Your cluster name

  • A hash

  • A flag for the API version

  • A flag for the username you want to use to connect

It resembles the following string:

mongosh "mongodb+srv://YOUR_CLUSTER_NAME.YOUR_HASH.mongodb.net/" --apiVersion YOUR_API_VERSION --username YOUR_USERNAME

Note

Learn More

You can use other connection security options to connect to Atlas viamongosh. For information on connecting with a privateIP for peering or a Private Endpoint connection, refer to theAtlas Connect via mongoshdocumentation.

Connect to a Local Deployment on the Default Port

To connect to a MongoDB deployment running on localhost withdefault port 27017, run mongosh without any options:

This is equivalent to the following command:

mongosh "mongodb://localhost:27017"

Connect to a Local Deployment on a Non-Default Port

To specify a port to connect to on localhost, you can use either:

  • A connection string with thechosen port

  • The --port command-line option

For example, the following commands connect to a deployment running onlocalhost port 28015:

mongosh "mongodb://localhost:28015"

mongosh --port 28015

Connect to a Deployment on a Remote Host

To specify a remote host and port, you can use either:

  • A connection string with thechosen host and port.

  • The --host and --port command-line options. If you omit the--port option, mongosh uses the default port 27017.

For example, the following commands connect to a MongoDB deploymentrunning on host mongodb0.example.com and port 28015:

mongosh "mongodb://mongodb0.example.com:28015"

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

Note

Connect to MongoDB Atlas

If your remote host is an Atlas cluster, you can copy yourconnection string from the Atlas UI. To learn more, seeConnect to a Clusterin the Atlas documentation.

Specify Connection Options

Specify different connection options to connect to different types ofdeployments.

Connect With Authentication

To connect to a MongoDB deployment that requires authentication, use the--username and --authenticationDatabase options. mongosh prompts you for apassword, which it hides as you type.

For example, to authenticate as user alice on the admindatabase, run the following command:

mongosh "mongodb://mongodb0.example.com:28015" --username alice --authenticationDatabase admin

To provide a password as part of the connection command instead of usingthe prompt, use the --password option. Use thisoption for programmatic usage of mongosh, like a driver.

Tip

See also:

  • To enforce authentication on a deployment, seeEnable Access Control.

  • To provision access to a MongoDB deployment, see DatabaseUsers.

Connect with OpenID Connect

To connect to a deployment using OpenID Connect,use the --authenticationMechanism option and set it to MONGODB-OIDC.mongosh redirects you to a browser where you enter your identity provider'slog-in information.

For example, the following connects to a local deployment using MONGODB-OIDC:

mongosh "mongodb://localhost/" --authenticationMechanism MONGODB-OIDC

Connect with LDAP

To connect to a deployment using LDAP:

  • Set --username to a username thatrespects the security.ldap.authz.queryTemplate, or anyconfigured security.ldap.userToDNMapping template.

  • Set --password to the appropriatepassword. If you do not specify the password to the--password command-line option, mongosh prompts you forthe password.

  • Set --authenticationDatabaseto $external.The $external argument must be placed in single quotes, notdouble quotes, to prevent the shell from interpreting $externalas a variable.

  • Set --authenticationMechanismto PLAIN.

Warning

When you use one-time passwords with LDAP authentication, addingthe connection string optionsmaxPoolSize=1&srvMaxHosts=1 to your connection string isrecommended to reduce the potential for connection failures.

Include the --host and--port of the MongoDB deployment, along withany other options relevant to your deployment.

For example, the following operation authenticates to a MongoDBdeployment running with LDAP authentication and authorization:

mongosh --username [email protected] --password --authenticationDatabase '$external' --authenticationMechanism "PLAIN" --host "mongodb.example.com" --port 27017

Connect to a Replica Set

To connect to a replica set, you can either:

  • Use the DNS Seedlist Connection Format.

  • Explicitly specify the replica set name and members in the connectionstring.

Option 1: DNS Seedlist Format

To use the DNS seedlist connection format, include the +srv modifierin your connection string.

For example, to connect to a replica set on server.example.com, runthe following command:

mongosh "mongodb+srv://server.example.com/"

Note

+srv TLS Behavior

When you use the +srv connection string modifier, MongoDBautomatically sets the --tls connection option totrue. To override this behavior, set --tls to false.

Option 2: Specify Members in Connection String

You can specify individual replica set members in theconnection string.

For example, to connect to a three-member replica set named replA,run the following command:

mongosh "mongodb://mongodb0.example.com.local:27017,mongodb1.example.com.local:27017,mongodb2.example.com.local:27017/?replicaSet=replA"

Note

directConnection Parameter Added Automatically

When you specify individual replica set members in the connectionstring, mongosh automatically adds the directConnection=trueparameter, unless at least one of the following is true:

  • The replicaSet query parameter is present in the connection string.

  • The connection string uses the mongodb+srv:// connection stringformat.

  • The connection string contains a seed list with multiple hosts.

  • The connection string already contains a directConnectionparameter.

When directConnection=true, all operations are run on the hostspecified in the connection URI.

Connect Using TLS

To connect to a deployment using TLS, you can either:

  • Use the DNS Seedlist Connection Format. The+srv connection string modifier automatically sets the tlsoption to true for the connection.

    For example, to connect to a DNS seedlist-defined replica set withtls enabled, run the following command:

    mongosh "mongodb+srv://server.example.com/"

  • Set the --tls option to true in the connectionstring.

    For example, to enable tls with a connection string option, runthe following command:

    mongosh "mongodb://mongodb0.example.com:28015/?tls=true"

  • Specify the --tls command-line option.

    For example, to connect to a remote host with tls enabled, run thefollowing command:

    mongosh "mongodb://mongodb0.example.com:28015" --tls

Connect to a Specific Database

To connect to a specific database, specify a database in yourconnection string URI path. Ifyou do not specify a database in your URI path, you connect to thetest database.

For example, to connect to a database called qa on localhost, run thefollowing command:

mongosh "mongodb://localhost:27017/qa"

Proxy Settings

To establish a connection with proxy configurations, you can use thefollowing environment variables:

Variable

Description

Example

MONGODB_PROXY

Proxy connections to mongodb:// and mongodb+srv:// URLs, suchas database clusters.

The following example sets the MONGODB_PROXY environment variable toproxy all MongoDB connections through a CONNECT proxy located atexample.com:8080 with TLS enabled.

export MONGODB_PROXY=https://example.com:8080

HTTP_PROXY

Proxy connections to http:// URLs. HTTP connections are mostlyused for OIDC authentication.

If you also set HTTPS_PROXY, the value of HTTPS_PROXY takesprecedence for all requests.

The following example sets the HTTP_PROXY environment variable toproxy HTTP connections through a CONNECT proxy located atexample.com:8080:

export HTTP_PROXY=http://example.com:8080

HTTPS_PROXY

Proxy connections to https:// URLs. HTTPS connections are mostlyused for OIDC authentication.

If you also set HTTP_PROXY, the value of HTTPS_PROXY takesprecedence for all requests.

The following example sets the HTTPS_PROXY environment variable toproxy all HTTPS connections through a CONNECT proxy located atlocalhost:8080 without TLS:

export HTTPS_PROXY=http://localhost:8080

ALL_PROXY

Proxy all connections to the specified URL.

The following example sets the ALL_PROXY environment variable toproxy all outbound network connections through a Socks5 proxy located atexample.com:1234 with credentials included in the URL:

export ALL_PROXY=socks5://username:[email protected]:1234

NO_PROXY

Comma-separated list of hostnames that should be excluded fromproxying.

The following example sets the NO_PROXY environment variable tobypass the proxy for connections to localhost andinternal-db.example.com.

export NO_PROXY=localhost,internal-db.example.com

Note

mongosh supports the following proxy types:

  • Socks5 proxies

  • HTTP proxies

  • CONNECT proxies

  • PAC URLs that resolve to one of the previouslylisted proxies

Connect to a Different Deployment

If you are already connected to a deployment in the MongoDB Shell, you canuse the Mongo() or connect() method to connect to a differentdeployment from within the MongoDB Shell.

To learn how to connect to a different deployment using these methods,see Open a New Connection.

Verify Current Connection

To verify your current database connection, use thedb.getMongo() method.

The method returns the connection string URI for your current connection.

Disconnect from a Deployment

To disconnect from a deployment and exit mongosh, perform one of thefollowing actions:

  • Type .exit, exit, or exit().

  • Type quit or quit().

  • Press Ctrl + D.

  • Press Ctrl + C twice.

Non-genuine Deployments

The shell displays a warning message when you connect to non-genuineMongoDB instances. Non-genuine instances may behave differently from theofficial MongoDB instances due to missing, inconsistent, or incompletefeatures.

Limitations

  • Kerberos authentication does not allowauthMechanismProperties=CANONICALIZE_HOST_NAME:true|false in theconnection string. Instead, use either:

    • authMechanismProperties=CANONICALIZE_HOST_NAME:forward

    • authMechanismProperties=CANONICALIZE_HOST_NAME:forwardAndReverse

    • authMechanismProperties=CANONICALIZE_HOST_NAME:none

  • mongosh currently only supports the zlibcompressor. The followingcompressors are not supported:

    • zstd

    • snappy

  • Starting in mongosh 2.0.0:

    For boolean values in connection strings, you:

    • must use true or false.

    • cannot use 1, y, yes, or t instead of true.

    • cannot use -1, 0, n, no, or f instead offalse.

BackVerify Windows PackagesNextConfigure
Connect to a Deployment (2024)
Top Articles
CoinMarketCap Launches $5 PPAY Learn & Earn Campaign With PlasmaFinance | CoinMarketCap
Coinbase Pro API - An Introductory Guide - AlgoTrading101 Blog
Skigebiet Portillo - Skiurlaub - Skifahren - Testberichte
Kostner Wingback Bed
His Lost Lycan Luna Chapter 5
Archived Obituaries
30 Insanely Useful Websites You Probably Don't Know About
Mr Tire Prince Frederick Md 20678
His Lost Lycan Luna Chapter 5
Craigslist Dog Sitter
Osrs But Damage
My.doculivery.com/Crowncork
Student Rating Of Teaching Umn
Planets Visible Tonight Virginia
World Cup Soccer Wiki
Charmeck Arrest Inquiry
Socket Exception Dunkin
Cnnfn.com Markets
Nalley Tartar Sauce
Unlv Mid Semester Classes
History of Osceola County
Napa Autocare Locator
라이키 유출
Ge-Tracker Bond
Why do rebates take so long to process?
1 Filmy4Wap In
Used Patio Furniture - Craigslist
Pioneer Library Overdrive
Wat is een hickmann?
800-695-2780
Table To Formula Calculator
They Cloned Tyrone Showtimes Near Showbiz Cinemas - Kingwood
Craigslist Auburn Al
Advance Auto Parts Stock Price | AAP Stock Quote, News, and History | Markets Insider
The value of R in SI units is _____?
Gr86 Forums
Truis Bank Near Me
Powerball lottery winning numbers for Saturday, September 7. $112 million jackpot
Mistress Elizabeth Nyc
Bitchinbubba Face
9781644854013
Hingham Police Scanner Wicked Local
Craigslist Com Panama City Fl
Best Restaurants West Bend
Actor and beloved baritone James Earl Jones dies at 93
Tunica Inmate Roster Release
Despacito Justin Bieber Lyrics
Todd Gutner Salary
Alba Baptista Bikini, Ethnicity, Marriage, Wedding, Father, Shower, Nazi
Europa Universalis 4: Army Composition Guide
Definition of WMT
Buildapc Deals
Latest Posts
Article information

Author: Ray Christiansen

Last Updated:

Views: 6041

Rating: 4.9 / 5 (49 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Ray Christiansen

Birthday: 1998-05-04

Address: Apt. 814 34339 Sauer Islands, Hirtheville, GA 02446-8771

Phone: +337636892828

Job: Lead Hospitality Designer

Hobby: Urban exploration, Tai chi, Lockpicking, Fashion, Gunsmithing, Pottery, Geocaching

Introduction: My name is Ray Christiansen, I am a fair, good, cute, gentle, vast, glamorous, excited person who loves writing and wants to share my knowledge and understanding with you.