connection – Tools for connecting to MongoDB

Tools for connecting to MongoDB.

See also

Module master_slave_connection for connecting to master-slave clusters, and Connecting to a Replica Set for an example of how to connect to a replica set.

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[, tz_aware=True]]]]]]]]])

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 port is not an instance of int. Raises ConnectionFailure if the connection cannot be made.

The host parameter can be a full mongodb URI, in addition to a simple hostname. It can also be a list of hostnames or URIs. Any port specified in the host string(s) will override the port parameter. If multiple mongodb URIs containing database or auth information are passed, the last database, username, and password present will be used.

Parameters:
  • host (optional): hostname or IPv4 address of the instance to connect to, or a mongodb URI, or a list of hostnames / mongodb URIs
  • 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
  • tz_aware (optional): if True, datetime instances returned as values in a document by this Connection will be timezone aware (otherwise they will be naive)

See also

end_request()

Changed in version 1.8: The host parameter can now be a full mongodb URI, in addition to a simple hostname. It can also be a list of hostnames or URIs.

New in version 1.8: The tz_aware parameter.

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

connections

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

DEPRECATED Can pass a mongodb URI directly to Connection() instead.

Changed in version 1.8: DEPRECATED

New in version 1.5.

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

DEPRECATED Can pass a list of hostnames to Connection() instead.

Changed in version 1.8: DEPRECATED

disconnect()

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

end_request()

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.

host

Current connected host.

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

port

Current connected port.

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

nodes

List of all known nodes.

Includes both nodes specified when the Connection was created, as well as nodes discovered through the replica set discovery mechanism.

New in version 1.8.

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

Default class to use for documents returned on this connection.

New in version 1.7.

tz_aware

Does this connection return timezone-aware datetimes?

See the tz_aware parameter to Connection().

New in version 1.8.

database_names()
Get a list of the names of all databases on the connected server.
drop_database(name_or_database)

Drop a database.

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

Parameters:
  • 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.

Parameters:
  • 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

Note

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

New in version 1.5.

server_info()
Get information about the MongoDB server we’re connected to.
start_request()

DEPRECATED all operations will start a request.

Changed in version 1.4: DEPRECATED

end_request()

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_cursor(cursor_id)

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.

Parameters:
  • cursor_id: id of cursor to close

See also

set_cursor_manager() and the cursor_manager module

kill_cursors(cursor_ids)

Send a kill cursors message with the given ids.

Raises TypeError if cursor_ids is not an instance of list.

Parameters:
  • cursor_ids: list of cursor ids to kill
set_cursor_manager(manager_class)

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.

Parameters:
  • manager_class: cursor manager to use

Previous topic

pymongo – Python driver for MongoDB

Next topic

database – Database level operations

This Page