database – Database level operations

Database level operations.

pymongo.auth.MECHANISMS = frozenset(['MONGODB-X509', 'DEFAULT', 'PLAIN', 'GSSAPI', 'MONGODB-CR', 'SCRAM-SHA-1'])

The authentication mechanisms supported by PyMongo.

pymongo.OFF = 0

No database profiling.

pymongo.SLOW_ONLY = 1

Only profile slow operations.

pymongo.ALL = 2

Profile all operations.

class pymongo.database.Database(client, name, codec_options=None, read_preference=None, write_concern=None)

Get a database by client and name.

Raises TypeError if name is not an instance of basestring (str in python 3). Raises InvalidName if name is not a valid database name.

Parameters:
  • client: A MongoClient instance.
  • name: The database name.
  • codec_options (optional): An instance of CodecOptions. If None (the default) client.codec_options is used.
  • read_preference (optional): The read preference to use. If None (the default) client.read_preference is used.
  • write_concern (optional): An instance of WriteConcern. If None (the default) client.write_concern is used.

See also

See general MongoDB documentation

databases

Changed in version 3.0: Added the codec_options, read_preference, and write_concern options. Database no longer returns an instance of Collection for attribute names with leading underscores. You must use dict-style lookups instead::

db[‘__my_collection__’]

Not:

db.__my_collection__
db[collection_name] || db.collection_name

Get the collection_name Collection of Database db.

Raises InvalidName if an invalid collection name is used.

Note

Use dictionary style access if collection_name is an attribute of the Database class eg: db[collection_name].

codec_options

Read only access to the CodecOptions of this instance.

read_preference

Read only access to the read preference of this instance.

Changed in version 3.0: The read_preference attribute is now read only.

write_concern

Read only access to the WriteConcern of this instance.

Changed in version 3.0: The write_concern attribute is now read only.

add_son_manipulator(manipulator)

Add a new son manipulator to this database.

DEPRECATED - add_son_manipulator is deprecated.

Changed in version 3.0: Deprecated add_son_manipulator.

add_user(name, password=None, read_only=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
  • **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

Changed in version 2.5: Added kwargs support for optional fields introduced in MongoDB 2.4

Changed in version 2.2: Added support for read only users

authenticate(name, password=None, source=None, mechanism='DEFAULT', **kwargs)

Authenticate to use this database.

Authentication lasts for the life of the underlying client instance, or until logout() is called.

Raises TypeError if (required) name, (optional) password, or (optional) source is not an instance of basestring (str in python 3).

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.
Parameters:
  • name: the name of the user to authenticate.
  • password (optional): the password of the user to authenticate. Not used with GSSAPI or MONGODB-X509 authentication.
  • source (optional): the database to authenticate on. If not specified the current database is used.
  • mechanism (optional): See MECHANISMS for options. By default, use SCRAM-SHA-1 with MongoDB 3.0 and later, MONGODB-CR (MongoDB Challenge Response protocol) for older servers.
  • authMechanismProperties (optional): Used to specify authentication mechanism specific options. To specify the service name for GSSAPI authentication pass authMechanismProperties=’SERVICE_NAME:<service name>’

New in version 2.8: Use SCRAM-SHA-1 with MongoDB 3.0 and later.

Changed in version 2.5: Added the source and mechanism parameters. authenticate() now raises a subclass of PyMongoError if authentication fails due to invalid credentials or configuration issues.

See also

See general MongoDB documentation

authenticate

client

The client instance for this Database.

collection_names(include_system_collections=True)

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

Parameters:
  • include_system_collections (optional): if False list will not include system collections (e.g system.indexes)
command(command, value=1, check=True, allowable_errors=None, read_preference=Primary(), codec_options=CodecOptions(document_class=dict, tz_aware=False, uuid_representation=PYTHON_LEGACY, unicode_decode_error_handler='strict', tzinfo=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

  • read_preference: The read preference for this operation. See read_preferences for options.

  • codec_options: A CodecOptions instance.

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

Note

command() does not obey read_preference or codec_options. You must use the read_preference and codec_options parameters instead.

Changed in version 3.0: Removed the as_class, fields, uuid_subtype, tag_sets, and secondary_acceptable_latency_ms option. Removed compile_re option: PyMongo now always represents BSON regular expressions as Regex objects. Use try_compile() to attempt to convert from a BSON regular expression to a Python regular expression object. Added the codec_options parameter.

Changed in version 2.7: Added compile_re option. If set to False, PyMongo represented BSON regular expressions as Regex objects instead of attempting to compile BSON regular expressions as Python native regular expressions, thus preventing errors for some incompatible patterns, see PYTHON-500.

Changed in version 2.3: Added tag_sets and secondary_acceptable_latency_ms options.

Changed in version 2.2: Added support for as_class - the class you want to use for the resulting documents

See also

See general MongoDB documentation

commands

create_collection(name, codec_options=None, read_preference=None, write_concern=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. Supported options vary with MongoDB release. Some examples include:

  • “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)

See the MongoDB documentation for a full list of supported options by server version.

Parameters:
  • name: the name of the collection to create
  • codec_options (optional): An instance of CodecOptions. If None (the default) the codec_options of this Database is used.
  • read_preference (optional): The read preference to use. If None (the default) the read_preference of this Database is used.
  • write_concern (optional): An instance of WriteConcern. If None (the default) the write_concern of this Database is used.
  • **kwargs (optional): additional keyword arguments will be passed as options for the create collection command

Changed in version 3.0: Added the codec_options, read_preference, and write_concern options.

Changed in version 2.2: Removed deprecated argument: options

current_op(include_all=False)

Get information on operations currently running.

Parameters:
  • include_all (optional): if True also list currently idle operations in the result
dereference(dbref, **kwargs)

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
  • **kwargs (optional): any additional keyword arguments are the same as the arguments to find().
drop_collection(name_or_collection)

Drop a collection.

Parameters:
  • name_or_collection: the name of a collection to drop or the collection object itself
error()

DEPRECATED: Get the error if one occurred on the last operation.

This method is obsolete: all MongoDB write operations (insert, update, remove, and so on) use the write concern w=1 and report their errors by default.

Changed in version 2.8: Deprecated.

eval(code, *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

Warning

the eval command is deprecated in MongoDB 3.0 and will be removed in a future server version.

get_collection(name, codec_options=None, read_preference=None, write_concern=None)

Get a Collection with the given name and options.

Useful for creating a Collection with different codec options, read preference, and/or write concern from this Database.

>>> db.read_preference
Primary()
>>> coll1 = db.test
>>> coll1.read_preference
Primary()
>>> from pymongo import ReadPreference
>>> coll2 = db.get_collection(
...     'test', read_preference=ReadPreference.SECONDARY)
>>> coll2.read_preference
Secondary(tag_sets=None)
Parameters:
incoming_copying_manipulators

All incoming SON copying manipulators installed on this instance.

New in version 2.0.

incoming_manipulators

All incoming SON manipulators installed on this instance.

New in version 2.0.

last_status()

DEPRECATED: Get status information from the last operation.

This method is obsolete: all MongoDB write operations (insert, update, remove, and so on) use the write concern w=1 and report their errors by default.

Returns a SON object with status information.

Changed in version 2.8: Deprecated.

logout()

Deauthorize use of this database for this client instance.

name

The name of this Database.

outgoing_copying_manipulators

List all outgoing SON copying manipulators installed on this instance.

New in version 2.0.

outgoing_manipulators

List all outgoing SON manipulators installed on this instance.

New in version 2.0.

previous_error()

DEPRECATED: Get the most recent error on this database.

This method is obsolete: all MongoDB write operations (insert, update, remove, and so on) use the write concern w=1 and report their errors by default.

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

Changed in version 2.8: Deprecated.

profiling_info()

Returns a list containing current profiling information.

See also

See general MongoDB documentation

profiling

profiling_level()

Get the database’s current profiling level.

Returns one of (OFF, SLOW_ONLY, ALL).

See also

See general MongoDB documentation

profiling

remove_user(name)

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
reset_error_history()

DEPRECATED: Reset the error history of this database.

This method is obsolete: all MongoDB write operations (insert, update, remove, and so on) use the write concern w=1 and report their errors by default.

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

Changed in version 2.8: Deprecated.

set_profiling_level(level, slow_ms=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.

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 also

See general MongoDB documentation

profiling

system_js

A SystemJS helper for this Database.

See the documentation for SystemJS for more details.

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

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.
class pymongo.database.SystemJS(database)

Get a system js helper for the database database.

An instance of SystemJS can be created with an instance of Database through Database.system_js, manual instantiation of this class should not be necessary.

SystemJS instances allow for easy manipulation and access to server-side JavaScript:

>>> db.system_js.add1 = "function (x) { return x + 1; }"
>>> db.system.js.find({"_id": "add1"}).count()
1
>>> db.system_js.add1(5)
6.0
>>> del db.system_js.add1
>>> db.system.js.find({"_id": "add1"}).count()
0
list()

Get a list of the names of the functions stored in this database.