Create a MongoClient
Overview
To connect to a MongoDB deployment, you need two things:
A connection URI, also known as a connection string, which tells PyMongo which MongoDB deployment to connect to.
A MongoClient object, which creates the connection to the MongoDB deployment and lets you perform operations on it.
You can also use either of these components to customize the way PyMongo behaves while connected to MongoDB.
This guide shows you how to create a connection string and use a MongoClient
object
to connect to MongoDB.
Connection URI
A standard connection string includes the following components:
Component | Description |
---|---|
| Required. A prefix that identifies this as a string in the standard connection format. |
| Optional. Authentication credentials. If you include these, the client
authenticates the user against the database specified in |
| Required. The host and optional port number where MongoDB is running. If you don't
include the port number, the driver uses the default port, |
| Optional. The authentication database to use if the
connection string includes |
| Optional. A query string that specifies connection-specific
options as |
For more information about creating a connection string, see Connection Strings in the MongoDB Server documentation.
MongoClient
To create a connection to MongoDB, pass a connection URI as a string to the
MongoClient
constructor. In the
following example, the driver uses a sample connection URI to connect to a MongoDB
instance on port 27017
of localhost
:
from pymongo import MongoClient uri = "mongodb://localhost:27017/" client = MongoClient(uri)
Tip
Reusing Your Client
Because each MongoClient
object represents a pool of connections to the
database, most applications require only a single instance of
MongoClient
, even across multiple requests. However, if you fork
a process, the child process does need its own MongoClient
object.
To learn more, see the FAQ page.
API Documentation
To learn more about creating a MongoClient
object in PyMongo,
see the following API documentation: