MongoDB - Connect

In this tutorial we will discuss the different ways to connect to MongoDB.

Start MongoDB Service

In the previous tutorials, we have discussedhow to start the MongoDB service, you just need to execute the following command in the bin directory of the MongoDB installation directorymongodband that's it.

After starting, MongoDB outputs some necessary information and then no output, after which it waits for connections to be established. When a connection is established, it begins printing log information.

You can useMongoDB shellto connect to the MongoDB server. You can also use PHP to connect to MongoDB. In this tutorial we will use the MongoDB shell to connect to the MongoDB service, and in later chapters we will introduce how to connect to MongoDB services via PHP, Python, and Node.js.

Standard URI connection syntax:

mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]
  • mongodb://: protocol header, indicates the use of MongoDB.
  • [username:password@]: (optional) authentication information, including username and password.
  • host1[:port1][,...hostN[:portN]]: server address and port, which can be the address and port of one or more MongoDB servers.
  • /[defaultauthdb]: (optional) default authentication database.
  • [?options]: (optional) connection options.

The standard connection format includes multiple options, as shown below:

  • authSource: specifies the authentication database.
  • replicaSet: specifies the name of the replica set.
  • ssl: enables SSL connection (true or false).
  • readPreference: specifies the read preference, such asprimary, primaryPreferred, secondary, secondaryPreferred, nearest。
  • connectTimeoutMS: specifies the connection timeout (milliseconds).
  • socketTimeoutMS: specifies the socket timeout (milliseconds).

Connect to a local MongoDB instance (default port 27017):

mongodb://localhost

Connect to a local MongoDB instance, specifying a database:

mongodb://localhost/mydatabase

Connect to a local MongoDB instance using username and password:

mongodb://username:password@localhost/mydatabase

Connect to a remote MongoDB instance:

mongodb://remotehost:27017

Connect to a replica set:

mongodb://host1:27017,host2:27017,host3:27017/mydatabase?replicaSet=myReplicaSet

Connect to MongoDB using SSL:

mongodb://username:password@localhost:27017/mydatabase?ssl=true

Connect using 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 (Mongoose)

Example

<?php
require 'vendor/autoload.php'; // Include the Composer autoload file

$client = new MongoDB\Client("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");
        }
    }
}

Example

Connect to the MongoDB service using the default port.

mongodb://localhost

Connect to the MongoDB service via the shell:

./mongosh
Current Mongosh Log ID:    66792d6b87657ebec9ed70f1
Connecting to:        mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.2.9
Using MongoDB:        7.0.11
Using Mongosh:        2.2.9

At this point, go back and look at the window where you ran the./mongodcommand, and you can see from where it connected to the MongoDB server. You can see the following information:

……省略信息……
2015-09-25T17:22:27.336+0800 I CONTROL  [initandlisten] allocator: tcmalloc
2015-09-25T17:22:27.336+0800 I CONTROL  [initandlisten] options: { storage: { dbPath: "/data/db" } }
2015-09-25T17:22:27.350+0800 I NETWORK  [initandlisten] waiting for connections on port 27017
2015-09-25T17:22:36.012+0800 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:37310 #1 (1 connection now open)  # 该行表明一个来自本机的连接

……省略信息……

MongoDB Connection Command Format

To connect to the MongoDB server using a username and password, you must use the 'username:password@hostname/dbname' format, 'username' is the username, 'password' is the password.

Use username and password to connect and log in to the default database:

$ ./mongosh
MongoDB shell version: 4.0.9
connecting to: test

Connect to the local MongoDB service using user admin with password 123456. The output result is as follows:

> mongodb://admin:123456@localhost/
... 

Use username and password to connect and log in to a specified database, the format is as follows:

mongodb://admin:123456@localhost/test

More Connection Examples

Connect to the local database server; the port is the default one.

mongodb://localhost

Log in to the admin database on localhost with username fred and password foobar.

mongodb://fred:foobar@localhost

Log in to the baz database on localhost with username fred and password foobar.

mongodb://fred:foobar@localhost/baz

Connect to a replica pair, server 1 is example1.com, server 2 is example2.

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 are applied on the primary server and reads are distributed to the secondary servers.

mongodb://host1,host2,host3/?slaveOk=true

Connect directly to the first server, whether it is part of a replica set, or the primary server, or a secondary server.

mongodb://host1,host2,host3/?connect=direct;slaveOk=true

When your connection servers have priority and you also need to list all servers, you can use the connection method above.

Connect to localhost in safe mode:

mongodb://localhost/?safe=true

Connect to the replica set in safe mode, and wait for at least two replica servers to successfully write, with a timeout of 2 seconds.

mongodb://host1,host2,host3/?safe=true;w=2;wtimeoutMS=2000
Other extensions