database – Database level operations

Database level operations.

pymongo.OFF
No database profiling.
pymongo.SLOW_ONLY
Only profile slow operations.
pymongo.ALL
Profile all operations.
class pymongo.database.Database(connection, name)

Get a database by connection and name.

Raises TypeError if name is not an instance of basestring. Raises InvalidName if name is not a valid database name.

Parameters:
  • connection: a Connection instance
  • name: database name

See general MongoDB documentation

databases

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)

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: the password of the user to create

New in version 1.4.

authenticate(name, password)

Authenticate to use this database.

Once authenticated, the user has full read and write access to this database. Raises TypeError if either name or password is not an instance of (str, unicode). Authentication lasts for the life of the database connection, 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

Currently, authentication is per socket. This means that there are a couple of situations in which re-authentication is necessary:

Warning

Currently, calls to end_request() will lead to unpredictable behavior in combination with auth. The socket owned by the calling thread will be returned to the pool, so whichever thread uses that socket next will have whatever permissions were granted to the calling thread.

Parameters:
  • name: the name of the user to authenticate
  • password: the password of the user to authenticate

See general MongoDB documentation

authenticate

collection_names()
Get a list of all the collection names in this database.
command(command, value=1, check=True, allowable_errors=[], _sock=None, **kwargs)

Issue a MongoDB command.

Send command command to the database and return the response. If command is an instance of basestring 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

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

Changed in version 1.6: Added the value argument for string commands, and keyword arguments for additional command options.

Changed in version 1.5: command can be a string in addition to a full document.

New in version 1.4.

See general MongoDB documentation

commands

connection

The Connection instance for this Database.

Changed in version 1.3: connection is now a property rather than a method. The connection() method is deprecated.

create_collection(name, options=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). must be less than or equal to 10000000000. 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
  • options: DEPRECATED options to use on the new collection
  • **kwargs (optional): additional keyword arguments will be passed as options for the create collection command

Changed in version 1.5: deprecating options in favor of kwargs

dereference(dbref)

Dereference a DBRef, getting the SON object it points to.

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

Parameters:
  • dbref: the reference
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()

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.

eval(code, *args)

Evaluate a JavaScript expression on the Mongo server.

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 (str, unicode, 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
last_status()

Get status information from the last operation.

Returns a SON object with status information.

logout()

Deauthorize use of this database for this connection.

Note that other databases may still be authorized.

name

The name of this Database.

Changed in version 1.3: name is now a property rather than a method. The name() method is deprecated.

previous_error()

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.

profiling_info()

Returns a list containing current profiling information.

See general MongoDB documentation

profiling

profiling_level()

Get the database’s current profiling level.

Returns one of (OFF, SLOW_ONLY, ALL).

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.

Paramaters:
  • name: the name of the user to remove

New in version 1.4.

reset_error_history()

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.

set_profiling_level(level)

Set the database’s profiling level.

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

Parameters:
  • level: the profiling level to use

See general MongoDB documentation

profiling

system_js

A SystemJS helper for this Database.

See the documentation for SystemJS for more details.

New in version 1.5.

validate_collection(name_or_collection)

Validate a collection.

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

class pymongo.database.SystemJS(database)

Get a system js helper for the database database.

An instance of SystemJS is automatically created for each Database instance as 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

Note

Requires server version >= 1.1.1

New in version 1.5.

Previous topic

connection – Tools for connecting to MongoDB

Next topic

collection – Collection level operations

This Page