MongoDB Connections
MongoDB is a database server: it runs in the foreground or background and waits for connections from the user. Thus, when you start MongoDB, you will see something like:
~/$ ./mongod # # some logging output # Tue Mar 9 11:15:43 waiting for connections on port 27017 Tue Mar 9 11:15:43 web admin interface listening on port 28017
It will stop printing output at this point but it hasn't frozen, it is merely waiting for connections on port 27017. Once you connect and start sending commands, it will continue to log what it's doing. You can use any of the MongoDB [drivers|Drivers] or [Mongo shell|Overview - The MongoDB Interactive Shell] to connect to the database.
You _cannot_ connect to MongoDB by going to [1] in your web browser. The database _cannot_ be accessed via HTTP on port 27017.
Standard Connection String Format
The uri scheme described on this page is not yet supported by all of the drivers. Refer to a specific driver's documentation to see how much (if any) of the standard connection uri is supported. All drivers support an alternative method of specifying connections if this format is not supported.
{dochub:connections}
mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/database]{code}
- mongodb:// is a required prefix to identify that this is a string in the standard connection format.
- username:password@ are optional. If given, the driver will attempt to login to a database after connecting to a database server.
- host1 is the only required part of the URI. It identifies a server address to connect to.
- :portX is optional and defaults to :27017 if not provided.
- /database is the name of the database to login to and thus is only relevant if the username:password@ syntax is used. If not specified the "admin" database will be used by default.
As many hosts as necessary may be specified (for connecting to replica pairs/sets).
Examples
Connect to a database server running locally on the default port:
mongodb://localhost
Connect and login to the admin database as user "fred" with password "foobar":
mongodb://fred:foobar@localhost
Connect and login to the "baz" database as user "fred" with password "foobar":
mongodb://fred:foobar@localhost/baz
Connect to a replica pair, with one server on example1.com and another server on example2.com:
mongodb://example1.com:27017,example2.com:27017
Connect to a replica set with three servers running on localhost (on ports 27017, 27018, and 27019):
mongodb://localhost,localhost:27018,localhost:27019
Connection Pooling
The server will use one thread per TCP connection, therefore it is highly recomended that your application use some sort of connection pooling. Luckily, most drivers handle this for you behind the scenes. One notable exception is setups where your app spawns a new process for each request, such as CGI and some configurations of PHP.
Taken from the MongoDB Connections documentation. Originally published under a Creative Commons license.