Easy Tutorial
❮ Mongodb Operators Type Mongodb Indexing ❯

MongoDB - Connection

In this tutorial, we will discuss different methods of connecting to MongoDB.

Starting MongoDB Service

In the previous tutorial, we have already discussed how to start the MongoDB service. You simply need to execute mongodb in the bin directory of your MongoDB installation directory.

After starting the service, MongoDB will output some necessary information and then wait for connections. Once a connection is established, it will start printing log information.

You can use the MongoDB shell to 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 sections, we will introduce how to connect to MongoDB service via PHP.

Standard URI Connection Syntax:

mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]

-

mongodb:// This is a fixed format and must be specified.

-

username:password@ Optional. If set, the driver will attempt to log in to the database after connecting to the server.

-

host1 At least one host must be specified. host1 is the only required part of the URI. It specifies the address of the server to connect to. If connecting to a replica set, specify multiple host addresses.

-

portX Optional. If not specified, the default port is 27017.

-

/database If username:password@ is specified, it connects and authenticates to the specified database. If not specified, it defaults to the test database.

-

?options Connection options. If not using /database, a / must be prepended. All connection options are name=value pairs separated by & or ; (semicolon).

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

Option Description
replicaSet=name Validates the name of the replica set. Implies connect=replicaSet.
slaveOk=true false true: In connect=direct mode, the driver will connect to the first machine, even if it is not the primary. In connect=replicaSet mode, the driver will send all write requests to the primary and distribute read operations to other secondary servers.<br> false: In connect=direct mode, the driver will automatically find the primary server. In connect=replicaSet mode, the driver will only connect to the primary server, and all read and write commands will connect to the primary server.
safe=true false true: After performing an update operation, the driver will send a getLastError command to ensure the update was successful. (Also refer to wtimeoutMS). false: The driver will not send a getLastError command to ensure the update was successful after each update.
w=n The driver adds { w : n } to the getLastError command. Applies to safe=true.
wtimeoutMS=ms The driver adds { wtimeout : ms } to the getLastError command. Applies to safe=true.
fsync=true false true: The driver adds { fsync : true } to the getLastError command. Applies to safe=true.<br> false: The driver will not add to the getLastError command.
journal=true false If set to true, syncs to the journal (writes to the physical medium before committing to the database). Applies to safe=true.
connectTimeoutMS=ms The time allowed to open a connection.
socketTimeoutMS=ms The time for sending and receiving sockets.

Example

Connecting to the MongoDB service using the default port:

mongodb://localhost

Connecting to the MongoDB service via shell:

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

At this point, if you return to the window where you ran the ./mongod command, you can see where the connection to the MongoDB server is coming from. You will see information like this:

……省略信息……
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) # This line indicates a connection from localhost

...omitted information...


MongoDB Connection Command Format

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

Connect and log in to the default database using a username and password:

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

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

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

Connect and log in to a specified database using a username and password, with the following format:

mongodb://admin:123456@localhost/test

More Connection Examples

Connect to a local database server on the default port.

mongodb://localhost

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

mongodb://fred:foobar@localhost

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

mongodb://fred:foobar@localhost/baz

Connect to a replica pair, with server1 as example1.com and server2 as example2.

mongodb://example1.com:27017,example2.com:27017

Connect to a replica set of three servers (ports 27017, 27018, and 27019):

mongodb://localhost,localhost:27018,localhost:27019

Connect to a replica set of three servers, with write operations directed to the primary and read queries distributed to the secondary servers.

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

Directly connect to the first server, whether it's part of a replica set or is a primary or secondary server.

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

When your connected server has priorities, and you need to list 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, waiting 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
❮ Mongodb Operators Type Mongodb Indexing ❯