connection – Tools for connecting to MongoDB

Tools for connecting to MongoDB.

To connect to a single instance of MongoDB use Connection. To connect to a replica pair use paired().

See also

Module master_slave_connection for connecting to master-slave clusters.

To get a Database instance from a Connection use either dictionary-style or attribute-style access:

>>> from pymongo import Connection
>>> c = Connection()
>>> c.test_database
Database(Connection('localhost', 27017), u'test_database')
>>> c['test-database']
Database(Connection('localhost', 27017), u'test-database')
class pymongo.connection.Connection([host='localhost'[, port=27017[, pool_size=None[, auto_start_request=None[, timeout=None[, slave_okay=False[, network_timeout=None[, document_class=dict]]]]]]]])

Create a new connection to a single MongoDB instance at host:port.

The resultant connection object has connection-pooling built in. It also performs auto-reconnection when necessary. If an operation fails because of a connection error, ConnectionFailure is raised. If auto-reconnection will be performed, AutoReconnect will be raised. Application code should handle this exception (recognizing that the operation failed) and then continue to execute.

Raises TypeError if host is not an instance of string or port is not an instance of int. Raises ConnectionFailure if the connection cannot be made.

  • host (optional): hostname or IPv4 address of the instance to connect to
  • port (optional): port number on which to connect
  • pool_size (optional): DEPRECATED
  • auto_start_request (optional): DEPRECATED
  • slave_okay (optional): is it okay to connect directly to and perform queries on a slave instance
  • timeout (optional): DEPRECATED
  • network_timeout (optional): timeout (in seconds) to use for socket operations - default is no timeout
  • document_class (optional): default class to use for documents returned from queries on this connection

See also


New in version 1.7: The document_class parameter.

Changed in version 1.4: DEPRECATED The pool_size, auto_start_request, and timeout parameters.

New in version 1.1: The network_timeout parameter.

See general MongoDB documentation


classmethod from_uri([uri='mongodb://localhost'])

Connect to a MongoDB instance(s) using the mongodb URI scheme.

The format for a MongoDB URI is documented here. Raises InvalidURI when given an invalid URI.

  • uri: URI identifying the MongoDB instance(s) to connect to

The remaining keyword arguments are the same as those accepted by Connection().

New in version 1.5.

classmethod paired(left[, right=('localhost', 27017)])

Open a new paired connection to Mongo.

Raises TypeError if either left or right is not a tuple of the form (host, port). Raises ConnectionFailure if the connection cannot be made.

  • left: (host, port) pair for the left MongoDB instance
  • right (optional): (host, port) pair for the right MongoDB instance

The remaining keyword arguments are the same as those accepted by Connection().


Disconnect from MongoDB.

Disconnecting will close all underlying sockets in the connection pool. If the Connection is used again it will be automatically re-opened. Care should be taken to make sure that disconnect() is not called in the middle of a sequence of operations in which ordering is important. This could lead to unexpected results.

See also


New in version 1.3.

c[db_name] || c.db_name

Get the db_name Database on Connection c.

Raises InvalidName if an invalid database name is used.


Current connected host.

Changed in version 1.3: host is now a property rather than a method.


Current connected port.

Changed in version 1.3: port is now a property rather than a method.

Is it okay for this connection to connect directly to a slave?

Default class to use for documents returned from queries on this connection.

New in version 1.7.

Get a list of the names of all databases on the connected server.

Drop a database.

Raises TypeError if name_or_database is not an instance of (str, unicode, Database)

  • name_or_database: the name of a database to drop, or a Database instance representing the database to drop
copy_database(from_name, to_name[, from_host=None[, username=None[, password=None]]])

Copy a database, potentially from another host.

Raises TypeError if from_name or to_name is not an instance of basestring. Raises InvalidName if to_name is not a valid database name.

If from_host is None the current host is used as the source. Otherwise the database is copied from from_host.

If the source database requires authentication, username and password must be specified.

  • from_name: the name of the source database
  • to_name: the name of the target database
  • from_host (optional): host name to copy from
  • username (optional): username for source database
  • password (optional): password for source database


Specifying username and password requires server version >= 1.3.3+.

New in version 1.5.

Get information about the MongoDB server we’re connected to.

DEPRECATED all operations will start a request.

Changed in version 1.4: DEPRECATED


Allow this thread’s connection to return to the pool.

Calling end_request() allows the socket that has been reserved for this thread to be returned to the pool. Other threads will then be able to re-use that socket. If your application uses many threads, or has long-running threads that infrequently perform MongoDB operations, then judicious use of this method can lead to performance gains. Care should be taken, however, to make sure that end_request() is not called in the middle of a sequence of operations in which ordering is important. This could lead to unexpected results.

One important case is when a thread is dying permanently. It is best to call end_request() when you know a thread is finished, as otherwise its socket will not be reclaimed.


Close a single database cursor.

Raises TypeError if cursor_id is not an instance of (int, long). What closing the cursor actually means depends on this connection’s cursor manager.

  • cursor_id: id of cursor to close

See also

set_cursor_manager() and the cursor_manager module


Send a kill cursors message with the given ids.

Raises TypeError if cursor_ids is not an instance of list.

  • cursor_ids: list of cursor ids to kill

Set this connection’s cursor manager.

Raises TypeError if manager_class is not a subclass of CursorManager. A cursor manager handles closing cursors. Different managers can implement different policies in terms of when to actually kill a cursor that has been closed.

  • manager_class: cursor manager to use

Previous topic

pymongo – Python driver for MongoDB

Next topic

database – Database level operations

This Page