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[, max_pool_size=10[, network_timeout=None[, document_class=dict[, tz_aware=False[, **kwargs]]]]]]])

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. For username and passwords reserved characters like ‘:’, ‘/’, ‘+’ and ‘@’ must be escaped following RFC 2396.

Parameters :
  • host (optional): hostname or IP address of the instance to connect to, or a mongodb URI, or a list of hostnames / mongodb URIs. If host is an IPv6 literal it must be enclosed in ‘[‘ and ‘]’ characters following the RFC2732 URL syntax (e.g. ‘[::1]’ for localhost)
  • port (optional): port number on which to connect
  • max_pool_size (optional): The maximum size limit for the connection pool.
  • 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)

Other optional parameters can be passed as keyword arguments:

  • safe: Use getlasterror for each write operation?
  • j or journal: Block until write operations have been commited to the journal. Ignored if the server is running without journaling. Implies safe=True.
  • w: (integer or string) If this is a replica set write operations won’t return until they have been replicated to the specified number or tagged set of servers. Implies safe=True.
  • wtimeout: Used in conjunction with j and/or w. Wait this many milliseconds for journal acknowledgement and/or write replication. Implies safe=True.
  • fsync: Force the database to fsync all files before returning When used with j the server awaits the next group commit before returning. Implies safe=True.
  • replicaSet: The name of the replica set to connect to. The driver will verify that the replica set it connects to matches this name. Implies that the hosts specified are a seed list and the driver should attempt to find all members of the set.
  • socketTimeoutMS: How long a send or receive on a socket can take before timing out.
  • connectTimeoutMS: How long a connection can take to be opened before timing out.
  • ssl: If True, create the connection to the server using SSL.
  • read_preference: The read preference for this connection. See ReadPreference for available options.
  • auto_start_request: If True (the default), each thread that accesses this Connection has a socket allocated to it for the thread’s lifetime. This ensures consistent reads, even if you read after an unsafe write.
  • use_greenlets (optional): if True, start_request() will ensure that the current greenlet uses the same socket for all operations until end_request()
  • slave_okay or slaveOk (deprecated): Use read_preference instead.

See also

end_request()

Changed in version 2.2: Added auto_start_request option back.

Changed in version 2.1: Support w = integer or string. Added ssl option. DEPRECATED slave_okay/slaveOk.

Changed in version 2.0: slave_okay is a pure keyword argument. Added support for safe, and getlasterror options as keyword arguments.

Changed in version 1.11: Added max_pool_size. Completely removed previously deprecated pool_size, auto_start_request and timeout parameters.

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.

New in version 1.1: The network_timeout parameter.

See general MongoDB documentation

connections

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.

close()

Alias for disconnect()

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 2.1.

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.

max_pool_size

The maximum pool size limit set for this connection.

New in version 1.11.

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.

read_preference

The read preference for this instance.

See ReadPreference for available options.

New in version 2.1.

slave_okay

DEPRECATED. Use read_preference instead.

Changed in version 2.1: Deprecated slave_okay.

New in version 2.0.

safe

Use getlasterror with every write operation?

New in version 2.0.

is_locked

Is this server locked? While locked, all write operations are blocked, although read operations may still be allowed. Use unlock() to unlock.

New in version 2.0.

get_lasterror_options()

Returns a dict of the getlasterror options set on this instance.

New in version 2.0.

set_lasterror_options(**kwargs)

Set getlasterror options for this instance.

Valid options include j=<bool>, w=<int>, wtimeout=<int>, and fsync=<bool>. Implies safe=True.

Parameters :
  • **kwargs: Options should be passed as keyword

    arguments (e.g. w=2, fsync=True)

New in version 2.0.

unset_lasterror_options(*options)

Unset getlasterror options for this instance.

If no options are passed unsets all getlasterror options. This does not set safe to False.

Parameters :
  • *options: The list of options to unset.

New in version 2.0.

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 basestring (str in python 3) or 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 (str in python 3). 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()

Ensure the current thread or greenlet always uses the same socket until it calls end_request(). This ensures consistent reads, even if you read after an unsafe write.

In Python 2.6 and above, or in Python 2.5 with “from __future__ import with_statement”, start_request() can be used as a context manager:

>>> connection = pymongo.Connection(auto_start_request=False)
>>> db = connection.test
>>> _id = db.test_collection.insert({}, safe=True)
>>> with connection.start_request():
...     for i in range(100):
...         db.test_collection.update({'_id': _id}, {'$set': {'i':i}})
...
...     # Definitely read the document after the final update completes
...     print db.test_collection.find({'_id': _id})

New in version 2.2: The Request return value. start_request() previously returned None

end_request()

Undo start_request() and allow this thread’s connection to return to the pool.

Calling end_request() allows the socket that has been reserved for this thread by start_request() 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.

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

Changed in version 2.1+: Deprecated support for external cursor managers.

fsync(**kwargs)

Flush all pending writes to datafiles.

Parameters :

Optional parameters can be passed as keyword arguments:

  • lock: If True lock the server to disallow writes.
  • async: If True don’t block while synchronizing.

Warning

async and lock can not be used together.

Warning

MongoDB does not support the async option on Windows and will raise an exception on that platform.

New in version 2.0.

unlock()

Unlock a previously locked server.

New in version 2.0.

Previous topic

pymongo – Python driver for MongoDB

Next topic

database – Database level operations

This Page