To begin interacting with a MongoDB database, the database service must be initialized. Navigate to the bin directory within your MongoDB installation folder and execute the mongod command. Upon execution, the server will initialize and wait for incoming connections. Once a client establishes a connection, the terminal will display relevant log entries.
While this guide utilizes the MongoDB shell for demonstration, connection strings are standardized across various drivers, including those for PHP, Python, and Node.js.
Standard URI Connection Syntax
MongoDB utilizes a uniform resource identifier (URI) string to define connection parameters. The standard structure is as follows:
mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
Parameter Breakdown:
mongodb://: A mandatory prefix indicating the protocol.username:password@: Optional credentials for authentication. If provided, the driver will attempt to authenticate against the specified database.host1: The hostname or IP address of the target server. At least one host is required. Multiple hosts should be listed for replica sets.portX: Optional port number. Defaults to27017if omitted./database: The authentication data base. If credentials are provided but this is omitted, the default is thetestdatabase.?options: Connection specific settings presented as key-value pairs (e.g.,key=value), separated by ampersands (&) or semicolons (;).
Connection Options
The connection string supports various options to modify behavior. The following table outlines common parameters:
| Option | Description |
|---|---|
replicaSet=name |
Verifies the name of the replica set. Implicitly sets the connection mode to replica set. |
slaveOk=true|false |
true: In direct mode, connects to the first available host regardles of status. In replica set mode, routes read operations to secondaries. false: In direct mode, finds the primary. In replica set mode, routes all traffic to the primary. |
safe=true|false |
true: The driver issues a getLastError command after write operations to confirm success. false: Does not wait for error confirmation after writes. |
w=n |
Appends { w : n } to the getLastError command. Requires safe=true. |
wtimeoutMS=ms |
Appends { wtimeout : ms } to the getLastError command. Requires safe=true. |
fsync=true|false |
true: Forces the driver to append { fsync : true } to getLastError. Requires safe=true. false: Does not apply fsync. |
journal=true|false |
If true, waits for the journal commit before reporting success. Requires safe=true. |
connectTimeoutMS=ms |
Time limit in milliseconds to establish a socket connection. |
socketTimeoutMS=ms |
Time limit in milliseconds for socket send or receive operations. |
Usage Examples
Connecting to the local instance on the default port:
mongodb://localhost
Connecting via the MongoDB Shell:
$ ./mongo
MongoDB shell version v4.4.0
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("...") }
MongoDB server version: 4.4.0
Authenticating with a username and password:
The syntax requires the credentials followed by the host. To connect as user db_admin with password securePass:
mongodb://db_admin:securePass@localhost/
To authenticate against a specific data base (e.g., app_data):
mongodb://db_admin:securePass@localhost/app_data
Advanced Scenarios
Connecting to a specific database with credentials:
mongodb://app_user:accessCode@192.168.1.10/production_db
Connecting to a Replica Pair:
mongodb://node1.example.com:27017,node2.example.com:27017
Connecting to a Replica Set (three nodes):
mongodb://primary,secondary1:27018,secondary2:27019
Replica Set with read preference set to secondaries:
mongodb://hostA,hostB,hostC/?slaveOk=true
Direct connection to a specific node (ignoring replica set state):
mongodb://hostA,hostB,hostC/?connect=direct;slaveOk=true
Safe Mode connection (Write Concern):
mongodb://localhost/?safe=true
Replica Set with Write Concern and Timeout:
Ensures writes are propagated to at least 2 nodes within 2 seconds:
mongodb://hostA,hostB,hostC/?safe=true;w=2;wtimeoutMS=2000