📜  mongodb uri 模板 (1)

📅  最后修改于: 2023-12-03 15:17:41.765000             🧑  作者: Mango

MongoDB URI Template

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.

Format

The MongoDB URI has the following format:

mongodb://username:password@host:port/database?options
  • mongodb:// - the protocol to be used
  • username - 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 located
  • port - the port on which the MongoDB database is running (default is 27017)
  • database - the name of the database to connect to
  • options - additional options that can be passed to the driver (optional)
Examples
Simple Connection String

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.

Connection String with Authentication

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.

Connection String with Replica Set

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.

Conclusion

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.