Database level operations.
The authentication mechanisms supported by PyMongo.
No database profiling.
Only profile slow operations.
Profile all operations.
Get a database by connection 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: |
|
---|
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].
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.
This attribute specifies which BSON Binary subtype is used when storing UUIDs. Historically UUIDs have been stored as BSON Binary subtype 3. This attribute is used to switch to the newer BSON Binary subtype 4. It can also be used to force legacy byte order and subtype compatibility with the Java and C# drivers. See the bson.binary module for all options.
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.
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.
Add a new son manipulator to this database.
Newly added manipulators will be applied before existing ones.
Parameters: |
|
---|
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: |
|
---|
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
New in version 1.4.
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
Parameters: |
|
---|
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.
Get a list of all the collection names in this database.
Parameters: |
|
---|
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: |
|
---|
Note
command ignores the network_timeout parameter.
Changed in version 2.7: Added compile_re option.
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
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.
The client instance for this Database.
Changed in version 1.3: connection is now a property rather than a method.
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: |
|
---|
Changed in version 2.2: Removed deprecated argument: options
Changed in version 1.5: deprecating options in favor of kwargs
Get information on operations currently running.
Parameters: |
|
---|
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: |
|
---|
Drop a collection.
Parameters: |
|
---|
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.
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: |
|
---|
List all incoming SON copying manipulators installed on this instance.
New in version 2.0.
List all incoming SON manipulators installed on this instance.
New in version 2.0.
Get status information from the last operation.
Returns a SON object with status information.
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().
The name of this Database.
Changed in version 1.3: name is now a property rather than a method.
List all outgoing SON copying manipulators installed on this instance.
New in version 2.0.
List all outgoing SON manipulators installed on this instance.
New in version 2.0.
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.
Returns a list containing current profiling information.
Get the database’s current profiling level.
Remove user name from this Database.
User name will no longer have permissions to access this Database.
Parameters: |
|
---|
New in version 1.4.
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 the database’s profiling level.
Parameters: |
|
---|
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).
A SystemJS helper for this Database.
See the documentation for SystemJS for more details.
New in version 1.5.
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: |
|
---|
Changed in version 1.11: validate_collection previously returned a string.
New in version 1.11: Added scandata and full options.
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
Note
Requires server version >= 1.1.1
New in version 1.5.
Get a list of the names of the functions stored in this database.
New in version 1.9.