3.8. MongoDB-connection

发布时间 :2025-10-25 12:32:57 UTC      

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

3.8.1. Start the MongoDB service

In the previous tutorial, we have discussed 如何启动 MongoDB 服务 You only need to execute it in the bin directory of the MongoDB installation directory mongodb That’s it.

After performing the startup operation, mongodb will not output any information after outputting some necessary information, then wait for the connection to be established, and when the connection is established, it will start printing log information.

You can use MongoDB shell to connect to the MongoDB server. You can also use PHP to connect to MongoDB. In this tutorial we will use MongoDB shell to connect to Mongodb services, and later chapters will show you how to connect to MongoDB services through 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 try to log in to the database after connecting to the database server

  • host1 At least one host must be specified. Host1 is the only one to fill in for this URI. It specifies the address to connect to the server. “if you want to connect to the replication set, specify multiple host addresses.”

  • portX Optional specified port. If left empty, the default is 27017.

  • /database If you specify a username:password@, connection and verify login to the specified database. If not specified, the test database is opened by default.

  • ?options It’s a connection option. If you do not use / database, you need to precede it with /. All connection options are key-value pairs name=value, separated by & or; (semicolon)

The standard connection format contains several options (options), as follows:

Option

Description

replicaSet=name

Verify the name of the replica set. Impliesconnect=replicaSet.

slaveOk=true|false

True: in connect=direct mode, the driver connects to the first machine, even if the server is not the master. In connect=replicaSet mode, the driver sends all write requests to the master and distributes read operations among other slave servers. False: in connect=direct mode, the driver automatically looks for the master server. In connect=replicaSet mode, the driver only connects to the master server, and all read and write commands are connected to the master server.

safe=true|false

True: after performing the update operation, the driver sends a getLastError command to ensure that the update is successful. (also refer to wtimeoutMS). False: after each update, the driver does not send a getLastError to ensure that the update is successful.

w=n

Drive to add {w: n} to the getLastError command. Apply to safe=true.

wtimeoutMS=ms

The driver adds {wtimeout: ms} to the getlasterror command. It is applied to safe=true.

fsync=true|false

True: driver to add {fsync: true} to the getlasterror command. It is applied to safe=true. False: drivers are not added to the getLastError command.

journal=true|false

If set to true, synchronize to journal (write to the entity before committing to the database). Apply to safe=true

connectTimeoutMS=ms

The time at which the connection can be opened.

socketTimeoutMS=ms

The time when the sockets was sent and received.

3.8.2. Example

Use the default port to connect to MongoDB’s services.

mongodb://localhost

Connect to the MongoDB service through shell:

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

At this time, you go back to check the run. ./mongod In the window of the command, you can see where to connect to the MongoDB server, and 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 with a user name and password, you must use’ username:password@hostname/dbname Format, ‘username’ is the user name, and’ password’ is the password.

Log in to the default database using a username and password connection:

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

Use user admin to connect to the local MongoDB service with a password of 123456. The output is as follows:

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

Log in to the specified database using a username and password connection in the following format:

mongodb://admin:123456@localhost/test

3.8.3. More connection instances

To connect to the local database server, the port is the default.

mongodb://localhost

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

mongodb://fred:foobar@localhost

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

mongodb://fred:foobar@localhost/baz

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

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

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

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

Connect three replica set servers, write operations are applied to the master server and distribute queries to the slave server.

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

Connect directly to the first server, whether it is part of the replica set or the master or slave server.

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

When your connection server has priority and all servers need to be listed, you can use the above connection method.

Connect to localhost in safe mode:

mongodb://localhost/?safe=true

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

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

Principles, Technologies, and Methods of Geographic Information Systems  102

In recent years, Geographic Information Systems (GIS) have undergone rapid development in both theoretical and practical dimensions. GIS has been widely applied for modeling and decision-making support across various fields such as urban management, regional planning, and environmental remediation, establishing geographic information as a vital component of the information era. The introduction of the “Digital Earth” concept has further accelerated the advancement of GIS, which serves as its technical foundation. Concurrently, scholars have been dedicated to theoretical research in areas like spatial cognition, spatial data uncertainty, and the formalization of spatial relationships. This reflects the dual nature of GIS as both an applied technology and an academic discipline, with the two aspects forming a mutually reinforcing cycle of progress.