MotorDatabase

class motor.MotorDatabase(connection, name)
db[collection_name] || db.collection_name

Get the collection_name MotorCollection of MotorDatabase db.

Raises InvalidName if an invalid collection name is used.

add_son_manipulator(manipulator)

Add a new son manipulator to this database.

Newly added manipulators will be applied before existing ones.

Parameters :
  • manipulator: the manipulator to add
add_user(name, password=None, read_only=None, callback=None, **kwargs)

Create user name with password password.

Add a new user with permissions for this Database.

Note

Will change the password if user name already exists.

Parameters :
  • name: the name of the user to create
  • password (optional): the password of the user to create. Can not be used with the userSource argument.
  • read_only (optional): if True the user will be read only
  • callback (optional): function taking (result, error), executed when operation completes
  • **kwargs (optional): optional fields for the user document (e.g. userSource, otherDBRoles, or roles). See http://docs.mongodb.org/manual/reference/privilege-documents for more information.

Note

The use of optional keyword arguments like userSource, otherDBRoles, or roles requires MongoDB >= 2.4.0

If a callback is passed, returns None, else returns a Future.

authenticate(name, password=None, source=None, mechanism='MONGODB-CR', callback=None)

Authenticate to use this database.

Raises TypeError if either name or password is not an instance of basestring (str in python 3). Authentication lasts for the life of the underlying client instance, or until logout() is called.

The “admin” database is special. Authenticating on “admin” gives access to all databases. Effectively, “admin” access means root access to the database.

Note

This method authenticates the current connection, and will also cause all new socket connections in the underlying client instance to be authenticated automatically.
  • Authenticating more than once on the same database with different credentials is not supported. You must call logout() before authenticating with new credentials.
  • When sharing a client instance between multiple threads, all threads will share the authentication. If you need different authentication profiles for different purposes you must use distinct client instances.
  • To get authentication to apply immediately to all existing sockets you may need to reset this client instance’s sockets using disconnect().
Parameters :
  • name: the name of the user to authenticate.
  • password (optional): the password of the user to authenticate. Not used with GSSAPI authentication.
  • source (optional): the database to authenticate on. If not specified the current database is used.
  • mechanism (optional): See MECHANISMS for options. Defaults to MONGODB-CR (MongoDB Challenge Response protocol)
  • callback (optional): function taking (result, error), executed when operation completes

See general MongoDB documentation

authenticate

If a callback is passed, returns None, else returns a Future.

collection_names(callback=None)

Get a list of all the collection names in this database.

Parameters :
  • callback (optional): function taking (result, error), executed when operation completes

If a callback is passed, returns None, else returns a Future.

command(command, value=1, check=True, allowable_errors=[], uuid_subtype=3, callback=None, **kwargs)

Issue a MongoDB command.

Send command command to the database and return the response. If command is an instance of basestring (str in python 3) then the command {command: value} will be sent. Otherwise, command must be an instance of dict and will be sent as is.

Any additional keyword arguments will be added to the final command document before it is sent.

For example, a command like {buildinfo: 1} can be sent using:

>>> db.command("buildinfo")

For a command where the value matters, like {collstats: collection_name} we can do:

>>> db.command("collstats", collection_name)

For commands that take additional arguments we can use kwargs. So {filemd5: object_id, root: file_root} becomes:

>>> db.command("filemd5", object_id, root=file_root)
Parameters :
  • command: document representing the command to be issued, or the name of the command (for simple commands only).

    Note

    the order of keys in the command document is significant (the “verb” must come first), so commands which require multiple keys (e.g. findandmodify) should use an instance of SON or a string and kwargs instead of a Python dict.

  • value (optional): value to use for the command verb when command is passed as a string

  • check (optional): check the response for errors, raising OperationFailure if there are any

  • allowable_errors: if check is True, error messages in this list will be ignored by error-checking

  • uuid_subtype (optional): The BSON binary subtype to use for a UUID used in this command.

  • read_preference: The read preference for this connection. See ReadPreference for available options.

  • tag_sets: Read from replica-set members with these tags. 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.

  • secondary_acceptable_latency_ms: Any replica-set member whose ping time is within secondary_acceptable_latency_ms of the nearest member may accept reads. Default 15 milliseconds. Ignored by mongos and must be configured on the command line. See the localThreshold option for more information.

  • callback (optional): function taking (result, error), executed when operation completes

  • **kwargs (optional): additional keyword arguments will be added to the command document before it is sent

See general MongoDB documentation

commands

If a callback is passed, returns None, else returns a Future.

create_collection(name, callback=None, **kwargs)

Create a new Collection in this database.

Normally collection creation is automatic. This method should only be used to specify options on creation. CollectionInvalid will be raised if the collection already exists.

Options should be passed as keyword arguments to this method. Any of the following options are valid:

  • “size”: desired initial size for the collection (in bytes). For capped collections this size is the max size of the collection.
  • “capped”: if True, this is a capped collection
  • “max”: maximum number of objects if capped (optional)
Parameters :
  • name: the name of the collection to create
  • callback (optional): function taking (result, error), executed when operation completes
  • **kwargs (optional): additional keyword arguments will be passed as options for the create collection command

If a callback is passed, returns None, else returns a Future.

current_op(include_all=False, callback=None)

Get information on operations currently running.

Parameters :
  • include_all (optional): if True also list currently idle operations in the result
  • callback (optional): function taking (result, error), executed when operation completes

If a callback is passed, returns None, else returns a Future.

dereference(dbref, callback=None)

Dereference a DBRef, getting the document it points to.

Raises TypeError if dbref is not an instance of DBRef. Returns a document, or None if the reference does not point to a valid document. Raises ValueError if dbref has a database specified that is different from the current database.

Parameters :
  • dbref: the reference
  • callback (optional): function taking (result, error), executed when operation completes

If a callback is passed, returns None, else returns a Future.

drop_collection(name_or_collection, callback=None)

Drop a collection.

Parameters :
  • name_or_collection: the name of a collection to drop or the collection object itself
  • callback (optional): function taking (result, error), executed when operation completes

If a callback is passed, returns None, else returns a Future.

error(callback=None)

Get a database error if one occured on the last operation.

Return None if the last operation was error-free. Otherwise return the error that occurred.

Parameters :
  • callback (optional): function taking (result, error), executed when operation completes

If a callback is passed, returns None, else returns a Future.

eval(code, callback=None, *args)

Evaluate a JavaScript expression in MongoDB.

Useful if you need to touch a lot of data lightly; in such a scenario the network transfer of the data could be a bottleneck. The code argument must be a JavaScript function. Additional positional arguments will be passed to that function when it is run on the server.

Raises TypeError if code is not an instance of basestring (str in python 3) or Code. Raises OperationFailure if the eval fails. Returns the result of the evaluation.

Parameters :
  • code: string representation of JavaScript code to be evaluated
  • args (optional): additional positional arguments are passed to the code being evaluated
  • callback (optional): function taking (result, error), executed when operation completes

If a callback is passed, returns None, else returns a Future.

last_status(callback=None)

Get status information from the last operation.

Returns a SON object with status information.

Parameters :
  • callback (optional): function taking (result, error), executed when operation completes

If a callback is passed, returns None, else returns a Future.

logout(callback=None)

Deauthorize use of this database for this client instance.

Note

Other databases may still be authenticated, and other existing socket connections may remain authenticated for this database unless you reset all sockets with disconnect().

Parameters :
  • callback (optional): function taking (result, error), executed when operation completes

If a callback is passed, returns None, else returns a Future.

previous_error(callback=None)

Get the most recent error to have occurred on this database.

Only returns errors that have occurred since the last call to Database.reset_error_history. Returns None if no such errors have occurred.

Parameters :
  • callback (optional): function taking (result, error), executed when operation completes

If a callback is passed, returns None, else returns a Future.

profiling_info(callback=None)

Returns a list containing current profiling information.

See general MongoDB documentation

profiling

Parameters :
  • callback (optional): function taking (result, error), executed when operation completes

If a callback is passed, returns None, else returns a Future.

profiling_level(callback=None)

Get the database’s current profiling level.

Returns one of (OFF, SLOW_ONLY, ALL).

See general MongoDB documentation

profiling

Parameters :
  • callback (optional): function taking (result, error), executed when operation completes

If a callback is passed, returns None, else returns a Future.

remove_user(name, callback=None)

Remove user name from this Database.

User name will no longer have permissions to access this Database.

Parameters :
  • name: the name of the user to remove
  • callback (optional): function taking (result, error), executed when operation completes

If a callback is passed, returns None, else returns a Future.

reset_error_history(callback=None)

Reset the error history of this database.

Calls to Database.previous_error will only return errors that have occurred since the most recent call to this method.

Parameters :
  • callback (optional): function taking (result, error), executed when operation completes

If a callback is passed, returns None, else returns a Future.

set_profiling_level(level, slow_ms=None, callback=None)

Set the database’s profiling level.

Parameters :
  • level: Specifies a profiling level, see list of possible values below.
  • slow_ms: Optionally modify the threshold for the profile to consider a query or operation. Even if the profiler is off queries slower than the slow_ms level will get written to the logs.
  • callback (optional): function taking (result, error), executed when operation completes

Possible level values:

Level Setting
OFF Off. No profiling.
SLOW_ONLY On. Only includes slow operations.
ALL On. Includes all operations.

Raises ValueError if level is not one of (OFF, SLOW_ONLY, ALL).

See general MongoDB documentation

profiling

If a callback is passed, returns None, else returns a Future.

validate_collection(name_or_collection, scandata=False, full=False, callback=None)

Validate a collection.

Returns a dict of validation info. Raises CollectionInvalid if validation fails.

With MongoDB < 1.9 the result dict will include a result key with a string value that represents the validation results. With MongoDB >= 1.9 the result key no longer exists and the results are split into individual fields in the result dict.

Parameters :
  • name_or_collection: A Collection object or the name of a collection to validate.
  • scandata: Do extra checks beyond checking the overall structure of the collection.
  • full: Have the server do a more thorough scan of the collection. Use with scandata for a thorough scan of the structure of the collection and the individual documents. Ignored in MongoDB versions before 1.9.
  • callback (optional): function taking (result, error), executed when operation completes

If a callback is passed, returns None, else returns a Future.

incoming_copying_manipulators

List all incoming SON copying manipulators installed on this instance.

incoming_manipulators

List all incoming SON manipulators installed on this instance.

name

The name of this Database.

outgoing_copying_manipulators

List all outgoing SON copying manipulators installed on this instance.

outgoing_manipulators

List all outgoing SON manipulators installed on this instance.

read_preference

The read preference mode for this instance.

See ReadPreference for available options.

secondary_acceptable_latency_ms

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.

Note

secondary_acceptable_latency_ms is ignored when talking to a replica set through a mongos. The equivalent is the localThreshold command line option.

tag_sets

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.

write_concern

The default write concern for this instance.

Supports dict style access for getting/setting write concern options. Valid options include:

  • w: (integer or string) If this is a replica set, write operations will block until they have been replicated to the specified number or tagged set of servers. w=<int> always includes the replica set primary (e.g. w=3 means write to the primary and wait until replicated to two secondaries). Setting w=0 disables write acknowledgement and all other write concern options.
  • wtimeout: (integer) Used in conjunction with w. Specify a value in milliseconds to control how long to wait for write propagation to complete. If replication does not complete in the given timeframe, a timeout exception is raised.
  • j: If True block until write operations have been committed to the journal. Ignored if the server is running without journaling.
  • fsync: If True force the database to fsync all files before returning. When used with j the server awaits the next group commit before returning.
>>> 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.

Previous topic

MotorReplicaSetClient – Connection to MongoDB replica set

Next topic

MotorCollection

This Page