📅  最后修改于: 2023-12-03 15:17:41.765000             🧑  作者: Mango
MongoDB is a popular NoSQL database used by many developers. When connecting to a MongoDB database, a URI (Uniform Resource Identifier) is required to specify the location and credentials of the database.
The MongoDB URI has the following format:
mongodb://username:password@host:port/database?options
mongodb://
- the protocol to be usedusername
- the username used to authenticate with the database (optional)password
- the password used to authenticate with the database (optional)host
- the hostname or IP address where the MongoDB database is locatedport
- the port on which the MongoDB database is running (default is 27017)database
- the name of the database to connect tooptions
- additional options that can be passed to the driver (optional)A simple connection string looks like this:
mongodb://localhost/mydatabase
This connects to a MongoDB server running on localhost
at the default port of 27017
, and uses the mydatabase
database.
To authenticate with a MongoDB server, include the username
and password
in the URI:
mongodb://myuser:mypassword@localhost/mydatabase
This connects to a MongoDB server running on localhost
at the default port of 27017
, and uses the mydatabase
database. The myuser
and mypassword
credentials are used to authenticate with the server.
To connect to a MongoDB replica set, include the name of the replica set in the URI:
mongodb://myuser:mypassword@host1:27017,host2:27017,host3:27017/mydatabase?replicaSet=myreplicaset
This connects to a MongoDB replica set consisting of three hosts: host1
, host2
, and host3
. The myuser
and mypassword
credentials are used to authenticate with the server, and the mydatabase
database is used. The replicaSet
option is set to myreplicaset
.
In conclusion, the MongoDB URI template is a powerful and flexible way to connect to a MongoDB database. With the ability to include authentication and replica set information, it provides everything a developer needs to get started with MongoDB.