Tools for connecting to MongoDB.
Warning
DEPRECATED: Please use mongo_client instead.
See also
Module master_slave_connection for connecting to master-slave clusters, and High Availability and PyMongo for an example of how to connect to a replica set, or specify a list of mongos instances for automatic failover.
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')
Create a new connection to a single MongoDB instance at host:port.
Warning
DEPRECATED: Connection is deprecated. Please use MongoClient instead.
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: |
Other optional parameters can be passed as keyword arguments:
Write Concern options:
Replica-set keyword arguments for connecting with a replica-set
- either directly or via a mongos:
(ignored by standalone mongod instances)
SSL configuration:
|
---|
See also
Changed in version 2.5: Added additional ssl options
Changed in version 2.3: Added support for failover between mongos seed list members.
Changed in version 2.2: Added auto_start_request option back. Added use_greenlets option.
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.
Disconnect from MongoDB.
Disconnecting will close all underlying sockets in the connection pool. If this instance 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.
Alias for disconnect()
Disconnecting will close all underlying sockets in the connection pool. If this instance 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 2.1.
Return False if there has been an error communicating with the server, else True.
This method attempts to check the status of the server with minimal I/O. The current thread / greenlet retrieves a socket from the pool (its request socket if it’s in a request, or a random idle socket if it’s not in a request) and checks whether calling select on it raises an error. If there are currently no idle sockets, alive() will attempt to actually connect to the server.
A more certain way to determine server availability is:
client.admin.command('ping')
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.
If this instance is connected to a standalone, a replica set primary, or the master of a master-slave set.
New in version 2.3.
If this instance is connected to mongos.
New in version 2.3.
The maximum number of sockets the pool will open concurrently.
When the pool has reached max_pool_size, operations block waiting for a socket to be returned to the pool. If waitQueueTimeoutMS is set, a blocked operation will raise ConnectionFailure after a timeout. By default waitQueueTimeoutMS is not set.
Warning
SIGNIFICANT BEHAVIOR CHANGE in 2.6. Previously, this parameter would limit only the idle sockets the pool would hold onto, not the number of open sockets. The default has also changed to 100.
Changed in version 2.6.
New in version 1.11.
List of all known nodes.
Nodes are either specified when this instance was created, or discovered through the replica set discovery mechanism.
New in version 1.8.
Is auto_start_request enabled?
Default class to use for documents returned from this client.
New in version 1.7.
Does this client return timezone-aware datetimes?
New in version 1.8.
Return the maximum size BSON object the connected server accepts in bytes. Defaults to 16MB if not connected to a server.
New in version 1.10.
Return the maximum message size the connected server accepts in bytes. Defaults to 32MB if not connected to a server.
New in version 2.6.
The minWireVersion reported by the server.
Returns 0 when connected to server versions prior to MongoDB 2.6.
New in version 2.7.
The maxWireVersion reported by the server.
Returns 0 when connected to server versions prior to MongoDB 2.6.
New in version 2.7.
The read preference mode for this instance.
See ReadPreference for available options.
New in version 2.1.
Set tag_sets to a list of dictionaries like [{‘dc’: ‘ny’}] to read only from members whose dc tag has the value "ny". To specify a priority-order for tag sets, provide a list of tag sets: [{'dc': 'ny'}, {'dc': 'la'}, {}]. A final, empty tag set, {}, means “read from any member that matches the mode, ignoring tags.” ReplicaSetConnection tries each set of tags in turn until it finds a set of tags with at least one matching member.
See also
New in version 2.3.
Any replica-set member whose ping time is within secondary_acceptable_latency_ms of the nearest member may accept reads. Defaults to 15 milliseconds.
See ReadPreference.
New in version 2.3.
Note
secondary_acceptable_latency_ms is ignored when talking to a replica set through a mongos. The equivalent is the localThreshold command line option.
The default write concern for this instance.
Supports dict style access for getting/setting write concern options. Valid options include:
>>> m = pymongo.MongoClient()
>>> m.write_concern
{}
>>> m.write_concern = {'w': 2, 'wtimeout': 1000}
>>> m.write_concern
{'wtimeout': 1000, 'w': 2}
>>> m.write_concern['j'] = True
>>> m.write_concern
{'wtimeout': 1000, 'j': True, 'w': 2}
>>> m.write_concern = {'j': True}
>>> m.write_concern
{'j': True}
>>> # Disable write acknowledgement and write concern
...
>>> m.write_concern['w'] = 0
Note
Accessing write_concern returns its value (a subclass of dict), not a copy.
Warning
If you are using Connection or ReplicaSetConnection make sure you explicitly set w to 1 (or a greater value) or safe to True. Unlike calling set_lasterror_options(), setting an option in write_concern does not implicitly set safe to True.
DEPRECATED. Use read_preference instead.
Changed in version 2.1: Deprecated slave_okay.
New in version 2.0.
DEPRECATED: Use the ‘w’ write_concern option instead.
Use getlasterror with every write operation?
New in version 2.0.
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 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 basestring (str in python 3) or Database.
Parameters: |
|
---|
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: |
|
---|
Note
Specifying username and password requires server version >= 1.3.3+.
New in version 1.5.
Get the database named in the MongoDB connection URI.
>>> uri = 'mongodb://host/my_database'
>>> client = MongoClient(uri)
>>> db = client.get_default_database()
>>> assert db.name == 'my_database'
Useful in scripts where you want to choose which database to use based only on the URI in a configuration file.
Get information about the MongoDB server we’re connected to.
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 unacknowledged 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:
>>> client = pymongo.MongoClient(auto_start_request=False)
>>> db = client.test
>>> _id = db.test_collection.insert({})
>>> with client.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})
If a thread or greenlet calls start_request multiple times, an equal number of calls to end_request() is required to end the request.
Changed in version 2.4: Now counts the number of calls to start_request and doesn’t end request until an equal number of calls to end_request.
New in version 2.2: The Request return value. start_request() previously returned None
Undo start_request(). If end_request() is called as many times as start_request(), the request is over and this thread’s connection returns to the pool. Extra calls to end_request() have no effect.
Ending a 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 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 client’s cursor manager.
Parameters: |
|
---|
Send a kill cursors message with the given ids.
Raises TypeError if cursor_ids is not an instance of list.
Parameters: |
|
---|
Set this client’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: |
|
---|
Changed in version 2.1+: Deprecated support for external cursor managers.
Flush all pending writes to datafiles.
Parameters: | Optional parameters can be passed as keyword arguments:
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 a previously locked server.
New in version 2.0.
DEPRECATED: Use write_concern instead.
Returns a dict of the getlasterror options set on this instance.
Changed in version 2.4: Deprecated get_lasterror_options.
New in version 2.0.
DEPRECATED: Use write_concern instead.
Set getlasterror options for this instance.
Valid options include j=<bool>, w=<int/string>, wtimeout=<int>, and fsync=<bool>. Implies safe=True.
Parameters: |
|
---|
Changed in version 2.4: Deprecated set_lasterror_options.
New in version 2.0.
DEPRECATED: Use write_concern instead.
Unset getlasterror options for this instance.
If no options are passed unsets all getlasterror options. This does not set safe to False.
Parameters: |
|
---|
Changed in version 2.4: Deprecated unset_lasterror_options.
New in version 2.0.