Introduction
In this tutorial, we will discuss various ways to connect to MongoDB.Starting the MongoDB Service
In previous tutorials, we have discussed how to start the MongoDB service. You just need to execute **mongod** in the bin directory of your MongoDB installation folder. After executing the startup command, MongoDB will output some necessary information and then stop showing any further output. It will then wait for incoming connections. Once a connection is established, it will begin printing log information. You can use the MongoDB shell to connect to the MongoDB server. You can also connect using PHP. In this tutorial, we will use the MongoDB shell to connect to the MongoDB service. In subsequent chapters, we will cover how to connect to MongoDB using PHP, Python, and Node.js.Standard URI Connection Syntax:
mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[?options]]
mongodb://: Protocol header indicating MongoDB usage.[username:password@]: (Optional) Authentication credentials including username and password.host1[:port1][,...hostN[:portN]]: Server address and port(s), which can be one or multiple MongoDB server addresses and ports.: (Optional) Default authentication database.[?options]: (Optional) Connection options.
authSource: Specifies the authentication database.replicaSet: Specifies the replica set name.ssl: Enables SSL connection (true or false).readPreference: Specifies read preference, such asprimary,primaryPreferred,secondary,secondaryPreferred,nearest.connectTimeoutMS: Specifies connection timeout in milliseconds.socketTimeoutMS: Specifies socket timeout in milliseconds.
Connecting to a Local MongoDB Instance (Default Port 27017)
mongodb://localhost
Connecting to a Local MongoDB Instance with Database Specified
mongodb://localhost/mydatabase
Connecting to a Local MongoDB Instance Using Username and Password
mongodb://username:password@localhost/mydatabase
Connecting to a Remote MongoDB Instance
mongodb://remotehost:27017
Connecting to a Replica Set
mongodb://host1:27017,host2:27017,host3:27017/mydatabase?replicaSet=myReplicaSet
Connecting to MongoDB Using SSL
mongodb://username:password@localhost:27017/mydatabase?ssl=true
Connecting with Multiple Options
mongodb://username:password@localhost:27017/mydatabase?authSource=admin&ssl=true
Python (PyMongo)
Example
from pymongo import MongoClient
client = MongoClient('mongodb://user:password@localhost:27017/mydatabase?authSource=admin')
db = client['mydatabase']
Node.js (Mongoose)
Example
const mongoose = require('mongoose');
mongoose.connect('mongodb://user:password@localhost:27017/mydatabase?authSource=admin', {
useNewUrlParser: true,
useUnifiedTopology: true
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
console.log('Connected to MongoDB');
});
PHP (MongoDB Driver)
Example
<?php
require 'vendor/autoload.php'; // Include Composer autoloader file
$client = new MongoDBClient("mongodb://localhost:27017"); // Connect to local MongoDB instance
$database = $client->selectDatabase('mydatabase'); // Select database
$collection = $database->selectCollection('mycollection'); // Select collection
// Insert document
$result = $collection->insertOne(['name' => 'Alice', 'age' => 30]);
echo "Inserted with Object ID '{$result->getInsertedId()}'";
// Query document
$document = $collection->findOne(['name' => 'Alice']);
echo "Found document: " . json_encode($document);
?>
Java
Example
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
public class MongoDBConnection {
public static void main(String[] args) {
String uri = "mongodb://user:password@localhost:27017/mydatabase?authSource=admin";
try (MongoClient mongoClient = MongoClients.create(uri)) {
MongoDatabase database = mongoClient.getDatabase("mydatabase");
System.out.println("Connected to MongoDB");
}
}
}
Examples
Connect to the MongoDB service using the default port.
mongodb://localhost
Connect to the MongoDB service via shell:
./mongosh Current Mongosh Log ID:66792d6b87657ebec9ed70f1Connecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.2.9Using MongoDB:7.0.11Using Mongosh:2.2.9
Now check the window where you ran the ./mongod command. You will see information about the connection source to the MongoDB server. You should see something like:
... omitted information ...2015-09-25T17:22:27.336+0800 I CONTROL allocator: tcmalloc 2015-09-25T17:22:27.336+0800 I CONTROL options: { storage: { dbPath: "/data/db" } }2015-09-25T17:22:27.350+0800 I NETWORK waiting for connections on port 270172015-09-25T17:22:36.012+0800 I NETWORK connection accepted from 127.0.0.1:37310 #1 (1 connection now open) # This line indicates a connection from localhost ... omitted information ...
MongoDB Connection Command Format
To connect to a MongoDB server using username and password, you must use the format 'username:password@hostname/dbname', where 'username' is the username and 'password' is the password.Connecting to the default database using username and password:
$ ./mongosh MongoDB shell version: 4.0.9 connecting to: test
Connecting to the local MongoDB service using user admin with password 123456. The output is as follows:
> mongodb://admin:123456@localhost/...
Connecting to a specified database using username and password:
mongodb://admin:123456@localhost/test
More Connection Examples
Connect to a local database server using the default port.
mongodb://localhost
Log in to the admin database on localhost using username fred and password foobar.
mongodb://fred:foobar@localhost
Log in to the baz database on localhost using username fred and password foobar.
mongodb://fred:foobar@localhost/baz
Connect to a replica pair: server1 is example1.com, server2 is example2.com.
mongodb://example1.com:27017,example2.com:27017
Connect to a replica set with three servers (ports 27017, 27018, and 27019):
mongodb://localhost,localhost:27018,localhost:27019
Connect to a replica set with three servers, write operations applied to the primary server, and queries distributed to secondary servers.
mongodb://host1,host2,host3/?slaveOk=true
Directly connect to the first server, whether it is part of a replica set or primary/secondary server.
mongodb://host1,host2,host3/?connect=direct;slaveOk=true
If your connection has priority and requires listing all servers, you can use the above connection method.
Connect to localhost in safe mode.
mongodb://localhost/?safe=true
Connect to a replica set in safe mode and wait for at least two replica servers to successfully write, with a timeout set to 2 seconds.
mongodb://host1,host2,host3/?safe=true;w=2;wtimeoutMS=2000
YouTip