desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'Get a collection of this database by name.
Raises InvalidName if an invalid collection name is used.
:Parameters:
- `name`: the name of the collection to get'
| def __getattr__(self, name):
| if name.startswith('_'):
raise AttributeError(('Database has no attribute %r. To access the %s collection, use database[%r].' % (name, name, name)))
return self.__getitem__(name)
|
'Get a collection of this database by name.
Raises InvalidName if an invalid collection name is used.
:Parameters:
- `name`: the name of the collection to get'
| def __getitem__(self, name):
| return Collection(self, name)
|
'Get a :class:`~pymongo.collection.Collection` with the given name
and options.
Useful for creating a :class:`~pymongo.collection.Collection` with
different codec options, read preference, and/or write concern from
this :class:`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:
- `name`: The name of the collection - a string.
- `codec_options` (optional): An instance of
:class:`~bson.codec_options.CodecOptions`. If ``None`` (the
default) the :attr:`codec_options` of this :class:`Database` is
used.
- `read_preference` (optional): The read preference to use. If
``None`` (the default) the :attr:`read_preference` of this
:class:`Database` is used. See :mod:`~pymongo.read_preferences`
for options.
- `write_concern` (optional): An instance of
:class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
default) the :attr:`write_concern` of this :class:`Database` is
used.
- `read_concern` (optional): An instance of
:class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
default) the :attr:`read_concern` of this :class:`Database` is
used.'
| def get_collection(self, name, codec_options=None, read_preference=None, write_concern=None, read_concern=None):
| return Collection(self, name, False, codec_options, read_preference, write_concern, read_concern)
|
'Get a Collection instance with the default settings.'
| def _collection_default_options(self, name, **kargs):
| wc = (self.write_concern if self.write_concern.acknowledged else WriteConcern())
return self.get_collection(name, codec_options=DEFAULT_CODEC_OPTIONS, read_preference=ReadPreference.PRIMARY, write_concern=wc)
|
'Create a new :class:`~pymongo.collection.Collection` in this
database.
Normally collection creation is automatic. This method should
only be used to specify options on
creation. :class:`~pymongo.errors.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
:class:`~bson.codec_options.CodecOptions`. If ``None`` (the
default) the :attr:`codec_options` of this :class:`Database` is
used.
- `read_preference` (optional): The read preference to use. If
``None`` (the default) the :attr:`read_preference` of this
:class:`Database` is used.
- `write_concern` (optional): An instance of
:class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
default) the :attr:`write_concern` of this :class:`Database` is
used.
- `read_concern` (optional): An instance of
:class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
default) the :attr:`read_concern` of this :class:`Database` is
used.
- `collation` (optional): An instance of
:class:`~pymongo.collation.Collation`.
- `**kwargs` (optional): additional keyword arguments will
be passed as options for the create collection command
.. versionchanged:: 3.4
Added the collation option.
.. versionchanged:: 3.0
Added the codec_options, read_preference, and write_concern options.
.. versionchanged:: 2.2
Removed deprecated argument: options'
| def create_collection(self, name, codec_options=None, read_preference=None, write_concern=None, read_concern=None, **kwargs):
| if (name in self.collection_names()):
raise CollectionInvalid(('collection %s already exists' % name))
return Collection(self, name, True, codec_options, read_preference, write_concern, read_concern, **kwargs)
|
'Apply incoming manipulators to `son`.'
| def _apply_incoming_manipulators(self, son, collection):
| for manipulator in self.__incoming_manipulators:
son = manipulator.transform_incoming(son, collection)
return son
|
'Apply incoming copying manipulators to `son`.'
| def _apply_incoming_copying_manipulators(self, son, collection):
| for manipulator in self.__incoming_copying_manipulators:
son = manipulator.transform_incoming(son, collection)
return son
|
'Apply manipulators to an incoming SON object before it gets stored.
:Parameters:
- `son`: the son object going into the database
- `collection`: the collection the son object is being saved in'
| def _fix_incoming(self, son, collection):
| son = self._apply_incoming_manipulators(son, collection)
son = self._apply_incoming_copying_manipulators(son, collection)
return son
|
'Apply manipulators to a SON object as it comes out of the database.
:Parameters:
- `son`: the son object coming out of the database
- `collection`: the collection the son object was saved in'
| def _fix_outgoing(self, son, collection):
| for manipulator in reversed(self.__outgoing_manipulators):
son = manipulator.transform_outgoing(son, collection)
for manipulator in reversed(self.__outgoing_copying_manipulators):
son = manipulator.transform_outgoing(son, collection)
return son
|
'Internal command helper.'
| def _command(self, sock_info, command, slave_ok=False, value=1, check=True, allowable_errors=None, read_preference=ReadPreference.PRIMARY, codec_options=DEFAULT_CODEC_OPTIONS, write_concern=None, parse_write_concern_error=False, **kwargs):
| if isinstance(command, string_type):
command = SON([(command, value)])
if ((sock_info.max_wire_version >= 5) and write_concern):
command['writeConcern'] = write_concern.document
command.update(kwargs)
return sock_info.command(self.__name, command, slave_ok, read_preference, codec_options, check, allowable_errors, parse_write_concern_error=parse_write_concern_error)
|
'Issue a MongoDB command.
Send command `command` to the database and return the
response. If `command` is an instance of :class:`basestring`
(:class:`str` in python 3) then the command {`command`: `value`}
will be sent. Otherwise, `command` must be an instance of
:class:`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 :class:`~bson.son.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
:class:`~pymongo.errors.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 :mod:`~pymongo.read_preferences` for options.
- `codec_options`: A :class:`~bson.codec_options.CodecOptions`
instance.
- `**kwargs` (optional): additional keyword arguments will
be added to the command document before it is sent
.. note:: :meth:`command` does **not** obey :attr:`read_preference`
or :attr:`codec_options`. You must use the `read_preference` and
`codec_options` parameters instead.
.. versionchanged:: 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 :class:`~bson.regex.Regex` objects. Use
:meth:`~bson.regex.Regex.try_compile` to attempt to convert from a
BSON regular expression to a Python regular expression object.
Added the `codec_options` parameter.
.. versionchanged:: 2.7
Added `compile_re` option. If set to False, PyMongo represented BSON
regular expressions as :class:`~bson.regex.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`_.
.. versionchanged:: 2.3
Added `tag_sets` and `secondary_acceptable_latency_ms` options.
.. versionchanged:: 2.2
Added support for `as_class` - the class you want to use for
the resulting documents
.. _PYTHON-500: https://jira.mongodb.org/browse/PYTHON-500
.. mongodoc:: commands'
| def command(self, command, value=1, check=True, allowable_errors=None, read_preference=ReadPreference.PRIMARY, codec_options=DEFAULT_CODEC_OPTIONS, **kwargs):
| client = self.__client
with client._socket_for_reads(read_preference) as (sock_info, slave_ok):
return self._command(sock_info, command, slave_ok, value, check, allowable_errors, read_preference, codec_options, **kwargs)
|
'Internal listCollections helper.'
| def _list_collections(self, sock_info, slave_okay, criteria=None):
| criteria = (criteria or {})
cmd = SON([('listCollections', 1), ('cursor', {})])
if criteria:
cmd['filter'] = criteria
if (sock_info.max_wire_version > 2):
coll = self['$cmd']
cursor = self._command(sock_info, cmd, slave_okay)['cursor']
return CommandCursor(coll, cursor, sock_info.address)
else:
coll = self['system.namespaces']
res = _first_batch(sock_info, coll.database.name, coll.name, criteria, 0, slave_okay, CodecOptions(), ReadPreference.PRIMARY, cmd, self.client._event_listeners)
data = res['data']
cursor = {'id': res['cursor_id'], 'firstBatch': data, 'ns': coll.full_name}
return CommandCursor(coll, cursor, sock_info.address, len(data))
|
'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``)'
| def collection_names(self, include_system_collections=True):
| with self.__client._socket_for_reads(ReadPreference.PRIMARY) as (sock_info, slave_okay):
wire_version = sock_info.max_wire_version
results = self._list_collections(sock_info, slave_okay)
names = [result['name'] for result in results]
if (wire_version <= 2):
names = [n[(len(self.__name) + 1):] for n in names if (n.startswith((self.__name + '.')) and ('$' not in n))]
if (not include_system_collections):
names = [name for name in names if (not name.startswith('system.'))]
return names
|
'Drop a collection.
:Parameters:
- `name_or_collection`: the name of a collection to drop or the
collection object itself
.. note:: The :attr:`~pymongo.database.Database.write_concern` of
this database is automatically applied to this operation when using
MongoDB >= 3.4.
.. versionchanged:: 3.4
Apply this database\'s write concern automatically to this operation
when connected to MongoDB >= 3.4.'
| def drop_collection(self, name_or_collection):
| name = name_or_collection
if isinstance(name, Collection):
name = name.name
if (not isinstance(name, string_type)):
raise TypeError(('name_or_collection must be an instance of %s' % (string_type.__name__,)))
self.__client._purge_index(self.__name, name)
with self.__client._socket_for_reads(ReadPreference.PRIMARY) as (sock_info, slave_ok):
return self._command(sock_info, 'drop', slave_ok, _unicode(name), allowable_errors=['ns not found'], write_concern=self.write_concern, parse_write_concern_error=True)
|
'Validate a collection.
Returns a dict of validation info. Raises CollectionInvalid if
validation fails.
: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.'
| def validate_collection(self, name_or_collection, scandata=False, full=False):
| name = name_or_collection
if isinstance(name, Collection):
name = name.name
if (not isinstance(name, string_type)):
raise TypeError(('name_or_collection must be an instance of %s or Collection' % (string_type.__name__,)))
result = self.command('validate', _unicode(name), scandata=scandata, full=full)
valid = True
if ('result' in result):
info = result['result']
if ((info.find('exception') != (-1)) or (info.find('corrupt') != (-1))):
raise CollectionInvalid(('%s invalid: %s' % (name, info)))
elif ('raw' in result):
for (_, res) in iteritems(result['raw']):
if ('result' in res):
info = res['result']
if ((info.find('exception') != (-1)) or (info.find('corrupt') != (-1))):
raise CollectionInvalid(('%s invalid: %s' % (name, info)))
elif (not res.get('valid', False)):
valid = False
break
elif (not result.get('valid', False)):
valid = False
if (not valid):
raise CollectionInvalid(('%s invalid: %r' % (name, result)))
return result
|
'Get information on operations currently running.
:Parameters:
- `include_all` (optional): if ``True`` also list currently
idle operations in the result'
| def current_op(self, include_all=False):
| cmd = SON([('currentOp', 1), ('$all', include_all)])
with self.__client._socket_for_writes() as sock_info:
if (sock_info.max_wire_version >= 4):
return sock_info.command('admin', cmd)
else:
spec = ({'$all': True} if include_all else {})
x = helpers._first_batch(sock_info, 'admin', '$cmd.sys.inprog', spec, (-1), True, self.codec_options, ReadPreference.PRIMARY, cmd, self.client._event_listeners)
return x.get('data', [None])[0]
|
'Get the database\'s current profiling level.
Returns one of (:data:`~pymongo.OFF`,
:data:`~pymongo.SLOW_ONLY`, :data:`~pymongo.ALL`).
.. mongodoc:: profiling'
| def profiling_level(self):
| result = self.command('profile', (-1))
assert ((result['was'] >= 0) and (result['was'] <= 2))
return result['was']
|
'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 |
| :data:`~pymongo.OFF` | Off. No profiling. |
| :data:`~pymongo.SLOW_ONLY` | On. Only includes slow operations. |
| :data:`~pymongo.ALL` | On. Includes all operations. |
Raises :class:`ValueError` if level is not one of
(:data:`~pymongo.OFF`, :data:`~pymongo.SLOW_ONLY`,
:data:`~pymongo.ALL`).
.. mongodoc:: profiling'
| def set_profiling_level(self, level, slow_ms=None):
| if ((not isinstance(level, int)) or (level < 0) or (level > 2)):
raise ValueError('level must be one of (OFF, SLOW_ONLY, ALL)')
if ((slow_ms is not None) and (not isinstance(slow_ms, int))):
raise TypeError('slow_ms must be an integer')
if (slow_ms is not None):
self.command('profile', level, slowms=slow_ms)
else:
self.command('profile', level)
|
'Returns a list containing current profiling information.
.. mongodoc:: profiling'
| def profiling_info(self):
| return list(self['system.profile'].find())
|
'**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.
.. versionchanged:: 2.8
Deprecated.'
| def error(self):
| warnings.warn('Database.error() is deprecated', DeprecationWarning, stacklevel=2)
error = self.command('getlasterror')
error_msg = error.get('err', '')
if (error_msg is None):
return None
if error_msg.startswith('not master'):
primary = self.__client.primary
if primary:
self.__client._reset_server_and_request_check(primary)
return error
|
'**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.
.. versionchanged:: 2.8
Deprecated.'
| def last_status(self):
| warnings.warn('last_status() is deprecated', DeprecationWarning, stacklevel=2)
return self.command('getlasterror')
|
'**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
:meth:`reset_error_history`. Returns None if no such errors have
occurred.
.. versionchanged:: 2.8
Deprecated.'
| def previous_error(self):
| warnings.warn('previous_error() is deprecated', DeprecationWarning, stacklevel=2)
error = self.command('getpreverror')
if (error.get('err', 0) is None):
return None
return error
|
'**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 :meth:`previous_error` will only return errors that have
occurred since the most recent call to this method.
.. versionchanged:: 2.8
Deprecated.'
| def reset_error_history(self):
| warnings.warn('reset_error_history() is deprecated', DeprecationWarning, stacklevel=2)
self.command('reseterror')
|
'Return the default user role for this database.'
| def _default_role(self, read_only):
| if (self.name == 'admin'):
if read_only:
return 'readAnyDatabase'
else:
return 'root'
elif read_only:
return 'read'
else:
return 'dbOwner'
|
'Use a command to create (if create=True) or modify a user.'
| def _create_or_update_user(self, create, name, password, read_only, **kwargs):
| opts = {}
if (read_only or (create and ('roles' not in kwargs))):
warnings.warn('Creating a user with the read_only option or without roles is deprecated in MongoDB >= 2.6', DeprecationWarning)
opts['roles'] = [self._default_role(read_only)]
elif read_only:
warnings.warn("The read_only option is deprecated in MongoDB >= 2.6, use 'roles' instead", DeprecationWarning)
if (password is not None):
if ('digestPassword' in kwargs):
raise ConfigurationError("The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option.")
opts['pwd'] = auth._password_digest(name, password)
opts['digestPassword'] = False
if (self.write_concern.acknowledged and self.write_concern.document):
opts['writeConcern'] = self.write_concern.document
opts.update(kwargs)
if create:
command_name = 'createUser'
else:
command_name = 'updateUser'
self.command(command_name, name, **opts)
|
'Uses v1 system to add users, i.e. saving to system.users.'
| def _legacy_add_user(self, name, password, read_only, **kwargs):
| system_users = self._collection_default_options('system.users')
user = (system_users.find_one({'user': name}) or {'user': name})
if (password is not None):
user['pwd'] = auth._password_digest(name, password)
if (read_only is not None):
user['readOnly'] = read_only
user.update(kwargs)
user.setdefault('_id', ObjectId())
try:
system_users.replace_one({'_id': user['_id']}, user, True)
except OperationFailure as exc:
if ('login' in str(exc)):
pass
elif (exc.details and ('getlasterror' in exc.details.get('note', ''))):
pass
else:
raise
|
'Create user `name` with password `password`.
Add a new user with permissions for this :class:`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
.. versionchanged:: 2.5
Added kwargs support for optional fields introduced in MongoDB 2.4
.. versionchanged:: 2.2
Added support for read only users'
| def add_user(self, name, password=None, read_only=None, **kwargs):
| if (not isinstance(name, string_type)):
raise TypeError(('name must be an instance of %s' % (string_type.__name__,)))
if (password is not None):
if (not isinstance(password, string_type)):
raise TypeError(('password must be an instance of %s' % (string_type.__name__,)))
if (len(password) == 0):
raise ValueError("password can't be empty")
if (read_only is not None):
read_only = common.validate_boolean('read_only', read_only)
if ('roles' in kwargs):
raise ConfigurationError('Can not use read_only and roles together')
try:
uinfo = self.command('usersInfo', name)
self._create_or_update_user((not uinfo['users']), name, password, read_only, **kwargs)
except OperationFailure as exc:
if (exc.code in common.COMMAND_NOT_FOUND_CODES):
self._legacy_add_user(name, password, read_only, **kwargs)
return
elif (exc.code == 13):
self._create_or_update_user(True, name, password, read_only, **kwargs)
else:
raise
|
'Remove user `name` from this :class:`Database`.
User `name` will no longer have permissions to access this
:class:`Database`.
:Parameters:
- `name`: the name of the user to remove'
| def remove_user(self, name):
| try:
cmd = SON([('dropUser', name)])
if (self.write_concern.acknowledged and self.write_concern.document):
cmd['writeConcern'] = self.write_concern.document
self.command(cmd)
except OperationFailure as exc:
if (exc.code in common.COMMAND_NOT_FOUND_CODES):
coll = self._collection_default_options('system.users')
coll.delete_one({'user': name})
return
raise
|
'**DEPRECATED**: Authenticate to use this database.
Authentication lasts for the life of the underlying client
instance, or until :meth:`logout` is called.
Raises :class:`TypeError` if (required) `name`, (optional) `password`,
or (optional) `source` is not an instance of :class:`basestring`
(:class:`str` in python 3).
.. note::
- This method authenticates the current connection, and
will also cause all new :class:`~socket.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 :meth:`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. Optional when
`mechanism` is MONGODB-X509 and the MongoDB server version is
>= 3.4.
- `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
:data:`~pymongo.auth.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>\'
.. versionchanged:: 3.5
Deprecated. Authenticating multiple users conflicts with support for
logical sessions in MongoDB 3.6. To authenticate as multiple users,
create multiple instances of MongoClient.
.. versionadded:: 2.8
Use SCRAM-SHA-1 with MongoDB 3.0 and later.
.. versionchanged:: 2.5
Added the `source` and `mechanism` parameters. :meth:`authenticate`
now raises a subclass of :class:`~pymongo.errors.PyMongoError` if
authentication fails due to invalid credentials or configuration
issues.
.. mongodoc:: authenticate'
| def authenticate(self, name=None, password=None, source=None, mechanism='DEFAULT', **kwargs):
| if ((name is not None) and (not isinstance(name, string_type))):
raise TypeError(('name must be an instance of %s' % (string_type.__name__,)))
if ((password is not None) and (not isinstance(password, string_type))):
raise TypeError(('password must be an instance of %s' % (string_type.__name__,)))
if ((source is not None) and (not isinstance(source, string_type))):
raise TypeError(('source must be an instance of %s' % (string_type.__name__,)))
common.validate_auth_mechanism('mechanism', mechanism)
validated_options = {}
for (option, value) in iteritems(kwargs):
(normalized, val) = common.validate_auth_option(option, value)
validated_options[normalized] = val
credentials = auth._build_credentials_tuple(mechanism, (source or self.name), name, password, validated_options)
self.client._cache_credentials(self.name, credentials, connect=True)
return True
|
'**DEPRECATED**: Deauthorize use of this database.'
| def logout(self):
| warnings.warn('Database.logout() is deprecated', DeprecationWarning, stacklevel=2)
self.client._purge_credentials(self.name)
|
'Dereference a :class:`~bson.dbref.DBRef`, getting the
document it points to.
Raises :class:`TypeError` if `dbref` is not an instance of
:class:`~bson.dbref.DBRef`. Returns a document, or ``None`` if
the reference does not point to a valid document. Raises
:class:`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
:meth:`~pymongo.collection.Collection.find`.'
| def dereference(self, dbref, **kwargs):
| if (not isinstance(dbref, DBRef)):
raise TypeError(('cannot dereference a %s' % type(dbref)))
if ((dbref.database is not None) and (dbref.database != self.__name)):
raise ValueError(('trying to dereference a DBRef that points to another database (%r not %r)' % (dbref.database, self.__name)))
return self[dbref.collection].find_one({'_id': dbref.id}, **kwargs)
|
'**DEPRECATED**: Evaluate a JavaScript expression in MongoDB.
: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.'
| def eval(self, code, *args):
| warnings.warn('Database.eval() is deprecated', DeprecationWarning, stacklevel=2)
if (not isinstance(code, Code)):
code = Code(code)
result = self.command('$eval', code, args=args)
return result.get('retval', None)
|
'This is only here so that some API misusages are easier to debug.'
| def __call__(self, *args, **kwargs):
| raise TypeError(("'Database' object is not callable. If you meant to call the '%s' method on a '%s' object it is failing because no such method exists." % (self.__name, self.__client.__class__.__name__)))
|
'**DEPRECATED**: Get a system js helper for the database `database`.
SystemJS will be removed in PyMongo 4.0.'
| def __init__(self, database):
| warnings.warn('SystemJS is deprecated', DeprecationWarning, stacklevel=2)
if (not database.write_concern.acknowledged):
database = database.client.get_database(database.name, write_concern=WriteConcern())
object.__setattr__(self, '_db', database)
|
'Get a list of the names of the functions stored in this database.'
| def list(self):
| return [x['_id'] for x in self._db.system.js.find(projection=['_id'])]
|
'Read only access to the :class:`~bson.codec_options.CodecOptions`
of this instance.'
| @property
def codec_options(self):
| return self.__codec_options
|
'Read only access to the :class:`~pymongo.write_concern.WriteConcern`
of this instance.
.. versionchanged:: 3.0
The :attr:`write_concern` attribute is now read only.'
| @property
def write_concern(self):
| return self.__write_concern
|
'Read only access to the read preference of this instance.
.. versionchanged:: 3.0
The :attr:`read_preference` attribute is now read only.'
| @property
def read_preference(self):
| return self.__read_preference
|
'Read only access to the read concern of this instance.
.. versionadded:: 3.2'
| @property
def read_concern(self):
| return self.__read_concern
|
'Parse an ismaster response from the server.'
| def __init__(self, doc):
| self._server_type = _get_server_type(doc)
self._doc = doc
self._is_writable = (self._server_type in (SERVER_TYPE.RSPrimary, SERVER_TYPE.Standalone, SERVER_TYPE.Mongos))
self._is_readable = ((self.server_type == SERVER_TYPE.RSSecondary) or self._is_writable)
|
'The complete ismaster command response document.
.. versionadded:: 3.4'
| @property
def document(self):
| return self._doc.copy()
|
'List of hosts, passives, and arbiters known to this server.'
| @property
def all_hosts(self):
| return set(imap(common.clean_node, itertools.chain(self._doc.get('hosts', []), self._doc.get('passives', []), self._doc.get('arbiters', []))))
|
'Replica set member tags or empty dict.'
| @property
def tags(self):
| return self._doc.get('tags', {})
|
'This server\'s opinion about who the primary is, or None.'
| @property
def primary(self):
| if self._doc.get('primary'):
return common.partition_node(self._doc['primary'])
else:
return None
|
'Replica set name or None.'
| @property
def replica_set_name(self):
| return self._doc.get('setName')
|
'Get / create a Mongo collection.
Raises :class:`TypeError` if `name` is not an instance of
:class:`basestring` (:class:`str` in python 3). Raises
:class:`~pymongo.errors.InvalidName` if `name` is not a valid
collection name. Any additional keyword arguments will be used
as options passed to the create command. See
:meth:`~pymongo.database.Database.create_collection` for valid
options.
If `create` is ``True``, `collation` is specified, or any additional
keyword arguments are present, a ``create`` command will be
sent. Otherwise, a ``create`` command will not be sent and the
collection will be created implicitly on first use.
:Parameters:
- `database`: the database to get a collection from
- `name`: the name of the collection to get
- `create` (optional): if ``True``, force collection
creation even without options being set
- `codec_options` (optional): An instance of
:class:`~bson.codec_options.CodecOptions`. If ``None`` (the
default) database.codec_options is used.
- `read_preference` (optional): The read preference to use. If
``None`` (the default) database.read_preference is used.
- `write_concern` (optional): An instance of
:class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
default) database.write_concern is used.
- `read_concern` (optional): An instance of
:class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
default) database.read_concern is used.
- `collation` (optional): An instance of
:class:`~pymongo.collation.Collation`. If a collation is provided,
it will be passed to the create collection command. This option is
only supported on MongoDB 3.4 and above.
- `**kwargs` (optional): additional keyword arguments will
be passed as options for the create collection command
.. versionchanged:: 3.4
Support the `collation` option.
.. versionchanged:: 3.2
Added the read_concern option.
.. versionchanged:: 3.0
Added the codec_options, read_preference, and write_concern options.
Removed the uuid_subtype attribute.
:class:`~pymongo.collection.Collection` no longer returns an
instance of :class:`~pymongo.collection.Collection` for attribute
names with leading underscores. You must use dict-style lookups
instead::
collection[\'__my_collection__\']
Not:
collection.__my_collection__
.. versionchanged:: 2.2
Removed deprecated argument: options
.. versionadded:: 2.1
uuid_subtype attribute
.. mongodoc:: collections'
| def __init__(self, database, name, create=False, codec_options=None, read_preference=None, write_concern=None, read_concern=None, **kwargs):
| super(Collection, self).__init__((codec_options or database.codec_options), (read_preference or database.read_preference), (write_concern or database.write_concern), (read_concern or database.read_concern))
if (not isinstance(name, string_type)):
raise TypeError(('name must be an instance of %s' % (string_type.__name__,)))
if ((not name) or ('..' in name)):
raise InvalidName('collection names cannot be empty')
if (('$' in name) and (not (name.startswith('oplog.$main') or name.startswith('$cmd')))):
raise InvalidName(("collection names must not contain '$': %r" % name))
if ((name[0] == '.') or (name[(-1)] == '.')):
raise InvalidName(("collection names must not start or end with '.': %r" % name))
if ('\x00' in name):
raise InvalidName('collection names must not contain the null character')
collation = validate_collation_or_none(kwargs.pop('collation', None))
self.__database = database
self.__name = _unicode(name)
self.__full_name = (_UJOIN % (self.__database.name, self.__name))
if (create or kwargs or collation):
self.__create(kwargs, collation)
self.__write_response_codec_options = self.codec_options._replace(unicode_decode_error_handler='replace', document_class=dict)
|
'Internal command helper.
:Parameters:
- `sock_info` - A SocketInfo instance.
- `command` - The command itself, as a SON instance.
- `slave_ok`: whether to set the SlaveOkay wire protocol bit.
- `codec_options` (optional) - An instance of
:class:`~bson.codec_options.CodecOptions`.
- `check`: raise OperationFailure if there are errors
- `allowable_errors`: errors to ignore if `check` is True
- `read_concern` (optional) - An instance of
:class:`~pymongo.read_concern.ReadConcern`.
- `write_concern`: An instance of
:class:`~pymongo.write_concern.WriteConcern`. This option is only
valid for MongoDB 3.4 and above.
- `parse_write_concern_error` (optional): Whether to parse a
``writeConcernError`` field in the command response.
- `collation` (optional) - An instance of
:class:`~pymongo.collation.Collation`.
:Returns:
# todo: don\'t return address
(result document, address of server the command was run on)'
| def _command(self, sock_info, command, slave_ok=False, read_preference=None, codec_options=None, check=True, allowable_errors=None, read_concern=DEFAULT_READ_CONCERN, write_concern=None, parse_write_concern_error=False, collation=None):
| return sock_info.command(self.__database.name, command, slave_ok, (read_preference or self.read_preference), (codec_options or self.codec_options), check, allowable_errors, read_concern=read_concern, write_concern=write_concern, parse_write_concern_error=parse_write_concern_error, collation=collation)
|
'Sends a create command with the given options.'
| def __create(self, options, collation):
| cmd = SON([('create', self.__name)])
if options:
if ('size' in options):
options['size'] = float(options['size'])
cmd.update(options)
with self._socket_for_writes() as sock_info:
self._command(sock_info, cmd, read_preference=ReadPreference.PRIMARY, write_concern=self.write_concern, parse_write_concern_error=True, collation=collation)
|
'Get a sub-collection of this collection by name.
Raises InvalidName if an invalid collection name is used.
:Parameters:
- `name`: the name of the collection to get'
| def __getattr__(self, name):
| if name.startswith('_'):
full_name = (_UJOIN % (self.__name, name))
raise AttributeError(("Collection has no attribute %r. To access the %s collection, use database['%s']." % (name, full_name, full_name)))
return self.__getitem__(name)
|
'The full name of this :class:`Collection`.
The full name is of the form `database_name.collection_name`.'
| @property
def full_name(self):
| return self.__full_name
|
'The name of this :class:`Collection`.'
| @property
def name(self):
| return self.__name
|
'The :class:`~pymongo.database.Database` that this
:class:`Collection` is a part of.'
| @property
def database(self):
| return self.__database
|
'Get a clone of this collection changing the specified settings.
>>> coll1.read_preference
Primary()
>>> from pymongo import ReadPreference
>>> coll2 = coll1.with_options(read_preference=ReadPreference.SECONDARY)
>>> coll1.read_preference
Primary()
>>> coll2.read_preference
Secondary(tag_sets=None)
:Parameters:
- `codec_options` (optional): An instance of
:class:`~bson.codec_options.CodecOptions`. If ``None`` (the
default) the :attr:`codec_options` of this :class:`Collection`
is used.
- `read_preference` (optional): The read preference to use. If
``None`` (the default) the :attr:`read_preference` of this
:class:`Collection` is used. See :mod:`~pymongo.read_preferences`
for options.
- `write_concern` (optional): An instance of
:class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
default) the :attr:`write_concern` of this :class:`Collection`
is used.
- `read_concern` (optional): An instance of
:class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
default) the :attr:`read_concern` of this :class:`Collection`
is used.'
| def with_options(self, codec_options=None, read_preference=None, write_concern=None, read_concern=None):
| return Collection(self.__database, self.__name, False, (codec_options or self.codec_options), (read_preference or self.read_preference), (write_concern or self.write_concern), (read_concern or self.read_concern))
|
'**DEPRECATED** - Initialize an unordered batch of write operations.
Operations will be performed on the server in arbitrary order,
possibly in parallel. All operations will be attempted.
:Parameters:
- `bypass_document_validation`: (optional) If ``True``, allows the
write to opt-out of document level validation. Default is
``False``.
Returns a :class:`~pymongo.bulk.BulkOperationBuilder` instance.
See :ref:`unordered_bulk` for examples.
.. note:: `bypass_document_validation` requires server version
**>= 3.2**
.. versionchanged:: 3.5
Deprecated. Use :meth:`~pymongo.collection.Collection.bulk_write`
instead.
.. versionchanged:: 3.2
Added bypass_document_validation support
.. versionadded:: 2.7'
| def initialize_unordered_bulk_op(self, bypass_document_validation=False):
| warnings.warn('initialize_unordered_bulk_op is deprecated', DeprecationWarning, stacklevel=2)
return BulkOperationBuilder(self, False, bypass_document_validation)
|
'**DEPRECATED** - Initialize an ordered batch of write operations.
Operations will be performed on the server serially, in the
order provided. If an error occurs all remaining operations
are aborted.
:Parameters:
- `bypass_document_validation`: (optional) If ``True``, allows the
write to opt-out of document level validation. Default is
``False``.
Returns a :class:`~pymongo.bulk.BulkOperationBuilder` instance.
See :ref:`ordered_bulk` for examples.
.. note:: `bypass_document_validation` requires server version
**>= 3.2**
.. versionchanged:: 3.5
Deprecated. Use :meth:`~pymongo.collection.Collection.bulk_write`
instead.
.. versionchanged:: 3.2
Added bypass_document_validation support
.. versionadded:: 2.7'
| def initialize_ordered_bulk_op(self, bypass_document_validation=False):
| warnings.warn('initialize_ordered_bulk_op is deprecated', DeprecationWarning, stacklevel=2)
return BulkOperationBuilder(self, True, bypass_document_validation)
|
'Send a batch of write operations to the server.
Requests are passed as a list of write operation instances (
:class:`~pymongo.operations.InsertOne`,
:class:`~pymongo.operations.UpdateOne`,
:class:`~pymongo.operations.UpdateMany`,
:class:`~pymongo.operations.ReplaceOne`,
:class:`~pymongo.operations.DeleteOne`, or
:class:`~pymongo.operations.DeleteMany`).
>>> for doc in db.test.find({}):
... print(doc)
{u\'x\': 1, u\'_id\': ObjectId(\'54f62e60fba5226811f634ef\')}
{u\'x\': 1, u\'_id\': ObjectId(\'54f62e60fba5226811f634f0\')}
>>> # DeleteMany, UpdateOne, and UpdateMany are also available.
>>> from pymongo import InsertOne, DeleteOne, ReplaceOne
>>> requests = [InsertOne({\'y\': 1}), DeleteOne({\'x\': 1}),
... ReplaceOne({\'w\': 1}, {\'z\': 1}, upsert=True)]
>>> result = db.test.bulk_write(requests)
>>> result.inserted_count
1
>>> result.deleted_count
1
>>> result.modified_count
0
>>> result.upserted_ids
{2: ObjectId(\'54f62ee28891e756a6e1abd5\')}
>>> for doc in db.test.find({}):
... print(doc)
{u\'x\': 1, u\'_id\': ObjectId(\'54f62e60fba5226811f634f0\')}
{u\'y\': 1, u\'_id\': ObjectId(\'54f62ee2fba5226811f634f1\')}
{u\'z\': 1, u\'_id\': ObjectId(\'54f62ee28891e756a6e1abd5\')}
:Parameters:
- `requests`: A list of write operations (see examples above).
- `ordered` (optional): If ``True`` (the default) requests will be
performed on the server serially, in the order provided. If an error
occurs all remaining operations are aborted. If ``False`` requests
will be performed on the server in arbitrary order, possibly in
parallel, and all operations will be attempted.
- `bypass_document_validation`: (optional) If ``True``, allows the
write to opt-out of document level validation. Default is
``False``.
:Returns:
An instance of :class:`~pymongo.results.BulkWriteResult`.
.. seealso:: :ref:`writes-and-ids`
.. note:: `bypass_document_validation` requires server version
**>= 3.2**
.. versionchanged:: 3.2
Added bypass_document_validation support
.. versionadded:: 3.0'
| def bulk_write(self, requests, ordered=True, bypass_document_validation=False):
| if (not isinstance(requests, list)):
raise TypeError('requests must be a list')
blk = _Bulk(self, ordered, bypass_document_validation)
for request in requests:
try:
request._add_to_bulk(blk)
except AttributeError:
raise TypeError(('%r is not a valid request' % (request,)))
bulk_api_result = blk.execute(self.write_concern.document)
if (bulk_api_result is not None):
return BulkWriteResult(bulk_api_result, True)
return BulkWriteResult({}, False)
|
'Internal legacy write helper.'
| def _legacy_write(self, sock_info, name, cmd, acknowledged, op_id, bypass_doc_val, func, *args):
| if (bypass_doc_val and (not acknowledged) and (sock_info.max_wire_version >= 4)):
raise OperationFailure('Cannot set bypass_document_validation with unacknowledged write concern')
listeners = self.database.client._event_listeners
publish = listeners.enabled_for_commands
if publish:
start = datetime.datetime.now()
(rqst_id, msg, max_size) = func(*args)
if publish:
duration = (datetime.datetime.now() - start)
listeners.publish_command_start(cmd, self.__database.name, rqst_id, sock_info.address, op_id)
start = datetime.datetime.now()
try:
result = sock_info.legacy_write(rqst_id, msg, max_size, acknowledged)
except Exception as exc:
if publish:
dur = ((datetime.datetime.now() - start) + duration)
if isinstance(exc, OperationFailure):
details = exc.details
if (details.get('ok') and ('n' in details)):
reply = message._convert_write_result(name, cmd, details)
listeners.publish_command_success(dur, reply, name, rqst_id, sock_info.address, op_id)
raise
else:
details = message._convert_exception(exc)
listeners.publish_command_failure(dur, details, name, rqst_id, sock_info.address, op_id)
raise
if publish:
if (result is not None):
reply = message._convert_write_result(name, cmd, result)
else:
reply = {'ok': 1}
duration = ((datetime.datetime.now() - start) + duration)
listeners.publish_command_success(duration, reply, name, rqst_id, sock_info.address, op_id)
return result
|
'Internal helper for inserting a single document.'
| def _insert_one(self, sock_info, doc, ordered, check_keys, manipulate, write_concern, op_id, bypass_doc_val):
| if manipulate:
doc = self.__database._apply_incoming_manipulators(doc, self)
if ((not isinstance(doc, RawBSONDocument)) and ('_id' not in doc)):
doc['_id'] = ObjectId()
doc = self.__database._apply_incoming_copying_manipulators(doc, self)
concern = (write_concern or self.write_concern).document
acknowledged = (concern.get('w') != 0)
command = SON([('insert', self.name), ('ordered', ordered), ('documents', [doc])])
if concern:
command['writeConcern'] = concern
if ((sock_info.max_wire_version > 1) and acknowledged):
if (bypass_doc_val and (sock_info.max_wire_version >= 4)):
command['bypassDocumentValidation'] = True
result = sock_info.command(self.__database.name, command, codec_options=self.__write_response_codec_options, check_keys=check_keys)
_check_write_command_response([(0, result)])
else:
self._legacy_write(sock_info, 'insert', command, acknowledged, op_id, bypass_doc_val, message.insert, self.__full_name, [doc], check_keys, acknowledged, concern, False, self.__write_response_codec_options)
if (not isinstance(doc, RawBSONDocument)):
return doc.get('_id')
|
'Internal insert helper.'
| def _insert(self, sock_info, docs, ordered=True, check_keys=True, manipulate=False, write_concern=None, op_id=None, bypass_doc_val=False):
| if isinstance(docs, collections.Mapping):
return self._insert_one(sock_info, docs, ordered, check_keys, manipulate, write_concern, op_id, bypass_doc_val)
ids = []
if manipulate:
def gen():
'Generator that applies SON manipulators to each document\n and adds _id if necessary.\n '
_db = self.__database
for doc in docs:
doc = _db._apply_incoming_manipulators(doc, self)
if (not (isinstance(doc, RawBSONDocument) or ('_id' in doc))):
doc['_id'] = ObjectId()
doc = _db._apply_incoming_copying_manipulators(doc, self)
ids.append(doc['_id'])
(yield doc)
else:
def gen():
'Generator that only tracks existing _ids.'
for doc in docs:
if (not isinstance(doc, RawBSONDocument)):
ids.append(doc.get('_id'))
(yield doc)
concern = (write_concern or self.write_concern).document
acknowledged = (concern.get('w') != 0)
command = SON([('insert', self.name), ('ordered', ordered)])
if concern:
command['writeConcern'] = concern
if (op_id is None):
op_id = message._randint()
if (bypass_doc_val and (sock_info.max_wire_version >= 4)):
command['bypassDocumentValidation'] = True
bwc = message._BulkWriteContext(self.database.name, command, sock_info, op_id, self.database.client._event_listeners)
if ((sock_info.max_wire_version > 1) and acknowledged):
results = message._do_batched_write_command((self.database.name + '.$cmd'), message._INSERT, command, gen(), check_keys, self.__write_response_codec_options, bwc)
_check_write_command_response(results)
else:
message._do_batched_insert(self.__full_name, gen(), check_keys, acknowledged, concern, (not ordered), self.__write_response_codec_options, bwc)
return ids
|
'Insert a single document.
>>> db.test.count({\'x\': 1})
0
>>> result = db.test.insert_one({\'x\': 1})
>>> result.inserted_id
ObjectId(\'54f112defba522406c9cc208\')
>>> db.test.find_one({\'x\': 1})
{u\'x\': 1, u\'_id\': ObjectId(\'54f112defba522406c9cc208\')}
:Parameters:
- `document`: The document to insert. Must be a mutable mapping
type. If the document does not have an _id field one will be
added automatically.
- `bypass_document_validation`: (optional) If ``True``, allows the
write to opt-out of document level validation. Default is
``False``.
:Returns:
- An instance of :class:`~pymongo.results.InsertOneResult`.
.. seealso:: :ref:`writes-and-ids`
.. note:: `bypass_document_validation` requires server version
**>= 3.2**
.. versionchanged:: 3.2
Added bypass_document_validation support
.. versionadded:: 3.0'
| def insert_one(self, document, bypass_document_validation=False):
| common.validate_is_document_type('document', document)
if (not (isinstance(document, RawBSONDocument) or ('_id' in document))):
document['_id'] = ObjectId()
with self._socket_for_writes() as sock_info:
return InsertOneResult(self._insert(sock_info, document, bypass_doc_val=bypass_document_validation), self.write_concern.acknowledged)
|
'Insert an iterable of documents.
>>> db.test.count()
0
>>> result = db.test.insert_many([{\'x\': i} for i in range(2)])
>>> result.inserted_ids
[ObjectId(\'54f113fffba522406c9cc20e\'), ObjectId(\'54f113fffba522406c9cc20f\')]
>>> db.test.count()
2
:Parameters:
- `documents`: A iterable of documents to insert.
- `ordered` (optional): If ``True`` (the default) documents will be
inserted on the server serially, in the order provided. If an error
occurs all remaining inserts are aborted. If ``False``, documents
will be inserted on the server in arbitrary order, possibly in
parallel, and all document inserts will be attempted.
- `bypass_document_validation`: (optional) If ``True``, allows the
write to opt-out of document level validation. Default is
``False``.
:Returns:
An instance of :class:`~pymongo.results.InsertManyResult`.
.. seealso:: :ref:`writes-and-ids`
.. note:: `bypass_document_validation` requires server version
**>= 3.2**
.. versionchanged:: 3.2
Added bypass_document_validation support
.. versionadded:: 3.0'
| def insert_many(self, documents, ordered=True, bypass_document_validation=False):
| if ((not isinstance(documents, collections.Iterable)) or (not documents)):
raise TypeError('documents must be a non-empty list')
inserted_ids = []
def gen():
'A generator that validates documents and handles _ids.'
for document in documents:
common.validate_is_document_type('document', document)
if (not isinstance(document, RawBSONDocument)):
if ('_id' not in document):
document['_id'] = ObjectId()
inserted_ids.append(document['_id'])
(yield (message._INSERT, document))
blk = _Bulk(self, ordered, bypass_document_validation)
blk.ops = [doc for doc in gen()]
blk.execute(self.write_concern.document)
return InsertManyResult(inserted_ids, self.write_concern.acknowledged)
|
'Internal update / replace helper.'
| def _update(self, sock_info, criteria, document, upsert=False, check_keys=True, multi=False, manipulate=False, write_concern=None, op_id=None, ordered=True, bypass_doc_val=False, collation=None):
| common.validate_boolean('upsert', upsert)
if manipulate:
document = self.__database._fix_incoming(document, self)
collation = validate_collation_or_none(collation)
concern = (write_concern or self.write_concern).document
acknowledged = (concern.get('w') != 0)
update_doc = SON([('q', criteria), ('u', document), ('multi', multi), ('upsert', upsert)])
if (collation is not None):
if (sock_info.max_wire_version < 5):
raise ConfigurationError('Must be connected to MongoDB 3.4+ to use collations.')
elif (not acknowledged):
raise ConfigurationError('Collation is unsupported for unacknowledged writes.')
else:
update_doc['collation'] = collation
command = SON([('update', self.name), ('ordered', ordered), ('updates', [update_doc])])
if concern:
command['writeConcern'] = concern
if ((sock_info.max_wire_version > 1) and acknowledged):
if (bypass_doc_val and (sock_info.max_wire_version >= 4)):
command['bypassDocumentValidation'] = True
result = sock_info.command(self.__database.name, command, codec_options=self.__write_response_codec_options).copy()
_check_write_command_response([(0, result)])
if (result.get('n') and ('upserted' not in result)):
result['updatedExisting'] = True
else:
result['updatedExisting'] = False
if ('upserted' in result):
result['upserted'] = result['upserted'][0]['_id']
return result
else:
return self._legacy_write(sock_info, 'update', command, acknowledged, op_id, bypass_doc_val, message.update, self.__full_name, upsert, multi, criteria, document, acknowledged, concern, check_keys, self.__write_response_codec_options)
|
'Replace a single document matching the filter.
>>> for doc in db.test.find({}):
... print(doc)
{u\'x\': 1, u\'_id\': ObjectId(\'54f4c5befba5220aa4d6dee7\')}
>>> result = db.test.replace_one({\'x\': 1}, {\'y\': 1})
>>> result.matched_count
1
>>> result.modified_count
1
>>> for doc in db.test.find({}):
... print(doc)
{u\'y\': 1, u\'_id\': ObjectId(\'54f4c5befba5220aa4d6dee7\')}
The *upsert* option can be used to insert a new document if a matching
document does not exist.
>>> result = db.test.replace_one({\'x\': 1}, {\'x\': 1}, True)
>>> result.matched_count
0
>>> result.modified_count
0
>>> result.upserted_id
ObjectId(\'54f11e5c8891e756a6e1abd4\')
>>> db.test.find_one({\'x\': 1})
{u\'x\': 1, u\'_id\': ObjectId(\'54f11e5c8891e756a6e1abd4\')}
:Parameters:
- `filter`: A query that matches the document to replace.
- `replacement`: The new document.
- `upsert` (optional): If ``True``, perform an insert if no documents
match the filter.
- `bypass_document_validation`: (optional) If ``True``, allows the
write to opt-out of document level validation. Default is
``False``.
- `collation` (optional): An instance of
:class:`~pymongo.collation.Collation`. This option is only supported
on MongoDB 3.4 and above.
:Returns:
- An instance of :class:`~pymongo.results.UpdateResult`.
.. note:: `bypass_document_validation` requires server version
**>= 3.2**
.. versionchanged:: 3.4
Added the `collation` option.
.. versionchanged:: 3.2
Added bypass_document_validation support
.. versionadded:: 3.0'
| def replace_one(self, filter, replacement, upsert=False, bypass_document_validation=False, collation=None):
| common.validate_is_mapping('filter', filter)
common.validate_ok_for_replace(replacement)
with self._socket_for_writes() as sock_info:
result = self._update(sock_info, filter, replacement, upsert, bypass_doc_val=bypass_document_validation, collation=collation)
return UpdateResult(result, self.write_concern.acknowledged)
|
'Update a single document matching the filter.
>>> for doc in db.test.find():
... print(doc)
{u\'x\': 1, u\'_id\': 0}
{u\'x\': 1, u\'_id\': 1}
{u\'x\': 1, u\'_id\': 2}
>>> result = db.test.update_one({\'x\': 1}, {\'$inc\': {\'x\': 3}})
>>> result.matched_count
1
>>> result.modified_count
1
>>> for doc in db.test.find():
... print(doc)
{u\'x\': 4, u\'_id\': 0}
{u\'x\': 1, u\'_id\': 1}
{u\'x\': 1, u\'_id\': 2}
:Parameters:
- `filter`: A query that matches the document to update.
- `update`: The modifications to apply.
- `upsert` (optional): If ``True``, perform an insert if no documents
match the filter.
- `bypass_document_validation`: (optional) If ``True``, allows the
write to opt-out of document level validation. Default is
``False``.
- `collation` (optional): An instance of
:class:`~pymongo.collation.Collation`. This option is only supported
on MongoDB 3.4 and above.
:Returns:
- An instance of :class:`~pymongo.results.UpdateResult`.
.. note:: `bypass_document_validation` requires server version
**>= 3.2**
.. versionchanged:: 3.4
Added the `collation` option.
.. versionchanged:: 3.2
Added bypass_document_validation support
.. versionadded:: 3.0'
| def update_one(self, filter, update, upsert=False, bypass_document_validation=False, collation=None):
| common.validate_is_mapping('filter', filter)
common.validate_ok_for_update(update)
with self._socket_for_writes() as sock_info:
result = self._update(sock_info, filter, update, upsert, check_keys=False, bypass_doc_val=bypass_document_validation, collation=collation)
return UpdateResult(result, self.write_concern.acknowledged)
|
'Update one or more documents that match the filter.
>>> for doc in db.test.find():
... print(doc)
{u\'x\': 1, u\'_id\': 0}
{u\'x\': 1, u\'_id\': 1}
{u\'x\': 1, u\'_id\': 2}
>>> result = db.test.update_many({\'x\': 1}, {\'$inc\': {\'x\': 3}})
>>> result.matched_count
3
>>> result.modified_count
3
>>> for doc in db.test.find():
... print(doc)
{u\'x\': 4, u\'_id\': 0}
{u\'x\': 4, u\'_id\': 1}
{u\'x\': 4, u\'_id\': 2}
:Parameters:
- `filter`: A query that matches the documents to update.
- `update`: The modifications to apply.
- `upsert` (optional): If ``True``, perform an insert if no documents
match the filter.
- `bypass_document_validation` (optional): If ``True``, allows the
write to opt-out of document level validation. Default is
``False``.
- `collation` (optional): An instance of
:class:`~pymongo.collation.Collation`. This option is only supported
on MongoDB 3.4 and above.
:Returns:
- An instance of :class:`~pymongo.results.UpdateResult`.
.. note:: `bypass_document_validation` requires server version
**>= 3.2**
.. versionchanged:: 3.4
Added the `collation` option.
.. versionchanged:: 3.2
Added bypass_document_validation support
.. versionadded:: 3.0'
| def update_many(self, filter, update, upsert=False, bypass_document_validation=False, collation=None):
| common.validate_is_mapping('filter', filter)
common.validate_ok_for_update(update)
with self._socket_for_writes() as sock_info:
result = self._update(sock_info, filter, update, upsert, check_keys=False, multi=True, bypass_doc_val=bypass_document_validation, collation=collation)
return UpdateResult(result, self.write_concern.acknowledged)
|
'Alias for :meth:`~pymongo.database.Database.drop_collection`.
The following two calls are equivalent:
>>> db.foo.drop()
>>> db.drop_collection("foo")'
| def drop(self):
| self.__database.drop_collection(self.__name)
|
'Internal delete helper.'
| def _delete(self, sock_info, criteria, multi, write_concern=None, op_id=None, ordered=True, collation=None):
| common.validate_is_mapping('filter', criteria)
concern = (write_concern or self.write_concern).document
acknowledged = (concern.get('w') != 0)
delete_doc = SON([('q', criteria), ('limit', int((not multi)))])
collation = validate_collation_or_none(collation)
if (collation is not None):
if (sock_info.max_wire_version < 5):
raise ConfigurationError('Must be connected to MongoDB 3.4+ to use collations.')
elif (not acknowledged):
raise ConfigurationError('Collation is unsupported for unacknowledged writes.')
else:
delete_doc['collation'] = collation
command = SON([('delete', self.name), ('ordered', ordered), ('deletes', [delete_doc])])
if concern:
command['writeConcern'] = concern
if ((sock_info.max_wire_version > 1) and acknowledged):
result = sock_info.command(self.__database.name, command, codec_options=self.__write_response_codec_options)
_check_write_command_response([(0, result)])
return result
else:
return self._legacy_write(sock_info, 'delete', command, acknowledged, op_id, False, message.delete, self.__full_name, criteria, acknowledged, concern, self.__write_response_codec_options, int((not multi)))
|
'Delete a single document matching the filter.
>>> db.test.count({\'x\': 1})
3
>>> result = db.test.delete_one({\'x\': 1})
>>> result.deleted_count
1
>>> db.test.count({\'x\': 1})
2
:Parameters:
- `filter`: A query that matches the document to delete.
- `collation` (optional): An instance of
:class:`~pymongo.collation.Collation`. This option is only supported
on MongoDB 3.4 and above.
:Returns:
- An instance of :class:`~pymongo.results.DeleteResult`.
.. versionchanged:: 3.4
Added the `collation` option.
.. versionadded:: 3.0'
| def delete_one(self, filter, collation=None):
| with self._socket_for_writes() as sock_info:
return DeleteResult(self._delete(sock_info, filter, False, collation=collation), self.write_concern.acknowledged)
|
'Delete one or more documents matching the filter.
>>> db.test.count({\'x\': 1})
3
>>> result = db.test.delete_many({\'x\': 1})
>>> result.deleted_count
3
>>> db.test.count({\'x\': 1})
0
:Parameters:
- `filter`: A query that matches the documents to delete.
- `collation` (optional): An instance of
:class:`~pymongo.collation.Collation`. This option is only supported
on MongoDB 3.4 and above.
:Returns:
- An instance of :class:`~pymongo.results.DeleteResult`.
.. versionchanged:: 3.4
Added the `collation` option.
.. versionadded:: 3.0'
| def delete_many(self, filter, collation=None):
| with self._socket_for_writes() as sock_info:
return DeleteResult(self._delete(sock_info, filter, True, collation=collation), self.write_concern.acknowledged)
|
'Get a single document from the database.
All arguments to :meth:`find` are also valid arguments for
:meth:`find_one`, although any `limit` argument will be
ignored. Returns a single document, or ``None`` if no matching
document is found.
The :meth:`find_one` method obeys the :attr:`read_preference` of
this :class:`Collection`.
:Parameters:
- `filter` (optional): a dictionary specifying
the query to be performed OR any other type to be used as
the value for a query for ``"_id"``.
- `*args` (optional): any additional positional arguments
are the same as the arguments to :meth:`find`.
- `**kwargs` (optional): any additional keyword arguments
are the same as the arguments to :meth:`find`.
>>> collection.find_one(max_time_ms=100)'
| def find_one(self, filter=None, *args, **kwargs):
| if ((filter is not None) and (not isinstance(filter, collections.Mapping))):
filter = {'_id': filter}
cursor = self.find(filter, *args, **kwargs)
for result in cursor.limit((-1)):
return result
return None
|
'Query the database.
The `filter` argument is a prototype document that all results
must match. For example:
>>> db.test.find({"hello": "world"})
only matches documents that have a key "hello" with value
"world". Matches can have other keys *in addition* to
"hello". The `projection` argument is used to specify a subset
of fields that should be included in the result documents. By
limiting results to a certain subset of fields you can cut
down on network traffic and decoding time.
Raises :class:`TypeError` if any of the arguments are of
improper type. Returns an instance of
:class:`~pymongo.cursor.Cursor` corresponding to this query.
The :meth:`find` method obeys the :attr:`read_preference` of
this :class:`Collection`.
:Parameters:
- `filter` (optional): a SON object specifying elements which
must be present for a document to be included in the
result set
- `projection` (optional): a list of field names that should be
returned in the result set or a dict specifying the fields
to include or exclude. If `projection` is a list "_id" will
always be returned. Use a dict to exclude fields from
the result (e.g. projection={\'_id\': False}).
- `skip` (optional): the number of documents to omit (from
the start of the result set) when returning the results
- `limit` (optional): the maximum number of results to
return
- `no_cursor_timeout` (optional): if False (the default), any
returned cursor is closed by the server after 10 minutes of
inactivity. If set to True, the returned cursor will never
time out on the server. Care should be taken to ensure that
cursors with no_cursor_timeout turned on are properly closed.
- `cursor_type` (optional): the type of cursor to return. The valid
options are defined by :class:`~pymongo.cursor.CursorType`:
- :attr:`~pymongo.cursor.CursorType.NON_TAILABLE` - the result of
this find call will return a standard cursor over the result set.
- :attr:`~pymongo.cursor.CursorType.TAILABLE` - the result of this
find call will be a tailable cursor - tailable cursors are only
for use with capped collections. They are not closed when the
last data is retrieved but are kept open and the cursor location
marks the final document position. If more data is received
iteration of the cursor will continue from the last document
received. For details, see the `tailable cursor documentation
<http://www.mongodb.org/display/DOCS/Tailable+Cursors>`_.
- :attr:`~pymongo.cursor.CursorType.TAILABLE_AWAIT` - the result
of this find call will be a tailable cursor with the await flag
set. The server will wait for a few seconds after returning the
full result set so that it can capture and return additional data
added during the query.
- :attr:`~pymongo.cursor.CursorType.EXHAUST` - the result of this
find call will be an exhaust cursor. MongoDB will stream batched
results to the client without waiting for the client to request
each batch, reducing latency. See notes on compatibility below.
- `sort` (optional): a list of (key, direction) pairs
specifying the sort order for this query. See
:meth:`~pymongo.cursor.Cursor.sort` for details.
- `allow_partial_results` (optional): if True, mongos will return
partial results if some shards are down instead of returning an
error.
- `oplog_replay` (optional): If True, set the oplogReplay query
flag.
- `batch_size` (optional): Limits the number of documents returned in
a single batch.
- `manipulate` (optional): **DEPRECATED** - If True (the default),
apply any outgoing SON manipulators before returning.
- `collation` (optional): An instance of
:class:`~pymongo.collation.Collation`. This option is only supported
on MongoDB 3.4 and above.
- `return_key` (optional): If True, return only the index keys in
each document.
- `show_record_id` (optional): If True, adds a field ``$recordId`` in
each document with the storage engine\'s internal record identifier.
- `snapshot` (optional): If True, prevents the cursor from returning
a document more than once because of an intervening write
operation.
- `hint` (optional): An index, in the same format as passed to
:meth:`~pymongo.collection.Collection.create_index` (e.g.
``[(\'field\', ASCENDING)]``). Pass this as an alternative to calling
:meth:`~pymongo.cursor.Cursor.hint` on the cursor to tell Mongo the
proper index to use for the query.
- `max_time_ms` (optional): Specifies a time limit for a query
operation. If the specified time is exceeded, the operation will be
aborted and :exc:`~pymongo.errors.ExecutionTimeout` is raised. Pass
this as an alternative to calling
:meth:`~pymongo.cursor.Cursor.max_time_ms` on the cursor.
- `max_scan` (optional): The maximum number of documents to scan.
Pass this as an alternative to calling
:meth:`~pymongo.cursor.Cursor.max_scan` on the cursor.
- `min` (optional): A list of field, limit pairs specifying the
inclusive lower bound for all keys of a specific index in order.
Pass this as an alternative to calling
:meth:`~pymongo.cursor.Cursor.min` on the cursor.
- `max` (optional): A list of field, limit pairs specifying the
exclusive upper bound for all keys of a specific index in order.
Pass this as an alternative to calling
:meth:`~pymongo.cursor.Cursor.max` on the cursor.
- `comment` (optional): A string or document. Pass this as an
alternative to calling :meth:`~pymongo.cursor.Cursor.comment` on the
cursor.
- `modifiers` (optional): **DEPRECATED** - A dict specifying
additional MongoDB query modifiers. Use the keyword arguments listed
above instead.
.. note:: There are a number of caveats to using
:attr:`~pymongo.cursor.CursorType.EXHAUST` as cursor_type:
- The `limit` option can not be used with an exhaust cursor.
- Exhaust cursors are not supported by mongos and can not be
used with a sharded cluster.
- A :class:`~pymongo.cursor.Cursor` instance created with the
:attr:`~pymongo.cursor.CursorType.EXHAUST` cursor_type requires an
exclusive :class:`~socket.socket` connection to MongoDB. If the
:class:`~pymongo.cursor.Cursor` is discarded without being
completely iterated the underlying :class:`~socket.socket`
connection will be closed and discarded without being returned to
the connection pool.
.. versionchanged:: 3.5
Added the options `return_key`, `show_record_id`, `snapshot`,
`hint`, `max_time_ms`, `max_scan`, `min`, `max`, and `comment`.
Deprecated the option `modifiers`.
.. versionchanged:: 3.4
Support the `collation` option.
.. versionchanged:: 3.0
Changed the parameter names `spec`, `fields`, `timeout`, and
`partial` to `filter`, `projection`, `no_cursor_timeout`, and
`allow_partial_results` respectively.
Added the `cursor_type`, `oplog_replay`, and `modifiers` options.
Removed the `network_timeout`, `read_preference`, `tag_sets`,
`secondary_acceptable_latency_ms`, `max_scan`, `snapshot`,
`tailable`, `await_data`, `exhaust`, `as_class`, and slave_okay
parameters. Removed `compile_re` option: PyMongo now always
represents BSON regular expressions as :class:`~bson.regex.Regex`
objects. Use :meth:`~bson.regex.Regex.try_compile` to attempt to
convert from a BSON regular expression to a Python regular
expression object. Soft deprecated the `manipulate` option.
.. versionchanged:: 2.7
Added `compile_re` option. If set to False, PyMongo represented BSON
regular expressions as :class:`~bson.regex.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`_.
.. versionadded:: 2.3
The `tag_sets` and `secondary_acceptable_latency_ms` parameters.
.. _PYTHON-500: https://jira.mongodb.org/browse/PYTHON-500
.. mongodoc:: find'
| def find(self, *args, **kwargs):
| return Cursor(self, *args, **kwargs)
|
'Scan this entire collection in parallel.
Returns a list of up to ``num_cursors`` cursors that can be iterated
concurrently. As long as the collection is not modified during
scanning, each document appears once in one of the cursors result
sets.
For example, to process each document in a collection using some
thread-safe ``process_document()`` function:
>>> def process_cursor(cursor):
... for document in cursor:
... # Some thread-safe processing function:
... process_document(document)
>>> # Get up to 4 cursors.
>>> cursors = collection.parallel_scan(4)
>>> threads = [
... threading.Thread(target=process_cursor, args=(cursor,))
... for cursor in cursors]
>>> for thread in threads:
... thread.start()
>>> for thread in threads:
... thread.join()
>>> # All documents have now been processed.
The :meth:`parallel_scan` method obeys the :attr:`read_preference` of
this :class:`Collection`.
:Parameters:
- `num_cursors`: the number of cursors to return
- `**kwargs`: additional options for the parallelCollectionScan
command can be passed as keyword arguments.
.. note:: Requires server version **>= 2.5.5**.
.. versionchanged:: 3.4
Added back support for arbitrary keyword arguments. MongoDB 3.4
adds support for maxTimeMS as an option to the
parallelCollectionScan command.
.. versionchanged:: 3.0
Removed support for arbitrary keyword arguments, since
the parallelCollectionScan command has no optional arguments.'
| def parallel_scan(self, num_cursors, **kwargs):
| cmd = SON([('parallelCollectionScan', self.__name), ('numCursors', num_cursors)])
cmd.update(kwargs)
with self._socket_for_reads() as (sock_info, slave_ok):
result = self._command(sock_info, cmd, slave_ok, read_concern=self.read_concern)
return [CommandCursor(self, cursor['cursor'], sock_info.address) for cursor in result['cursors']]
|
'Internal count helper.'
| def _count(self, cmd, collation=None):
| with self._socket_for_reads() as (sock_info, slave_ok):
res = self._command(sock_info, cmd, slave_ok, allowable_errors=['ns missing'], codec_options=self.__write_response_codec_options, read_concern=self.read_concern, collation=collation)
if (res.get('errmsg', '') == 'ns missing'):
return 0
return int(res['n'])
|
'Get the number of documents in this collection.
All optional count parameters should be passed as keyword arguments
to this method. Valid options include:
- `hint` (string or list of tuples): The index to use. Specify either
the index name as a string or the index specification as a list of
tuples (e.g. [(\'a\', pymongo.ASCENDING), (\'b\', pymongo.ASCENDING)]).
- `limit` (int): The maximum number of documents to count.
- `skip` (int): The number of matching documents to skip before
returning results.
- `maxTimeMS` (int): The maximum amount of time to allow the count
command to run, in milliseconds.
- `collation` (optional): An instance of
:class:`~pymongo.collation.Collation`. This option is only supported
on MongoDB 3.4 and above.
The :meth:`count` method obeys the :attr:`read_preference` of
this :class:`Collection`.
:Parameters:
- `filter` (optional): A query document that selects which documents
to count in the collection.
- `**kwargs` (optional): See list of options above.
.. versionchanged:: 3.4
Support the `collation` option.'
| def count(self, filter=None, **kwargs):
| cmd = SON([('count', self.__name)])
if (filter is not None):
if ('query' in kwargs):
raise ConfigurationError("can't pass both filter and query")
kwargs['query'] = filter
if (('hint' in kwargs) and (not isinstance(kwargs['hint'], string_type))):
kwargs['hint'] = helpers._index_document(kwargs['hint'])
collation = validate_collation_or_none(kwargs.pop('collation', None))
cmd.update(kwargs)
return self._count(cmd, collation)
|
'Create one or more indexes on this collection.
>>> from pymongo import IndexModel, ASCENDING, DESCENDING
>>> index1 = IndexModel([("hello", DESCENDING),
... ("world", ASCENDING)], name="hello_world")
>>> index2 = IndexModel([("goodbye", DESCENDING)])
>>> db.test.create_indexes([index1, index2])
["hello_world", "goodbye_-1"]
:Parameters:
- `indexes`: A list of :class:`~pymongo.operations.IndexModel`
instances.
.. note:: `create_indexes` uses the `createIndexes`_ command
introduced in MongoDB **2.6** and cannot be used with earlier
versions.
.. note:: The :attr:`~pymongo.collection.Collection.write_concern` of
this collection is automatically applied to this operation when using
MongoDB >= 3.4.
.. versionchanged:: 3.4
Apply this collection\'s write concern automatically to this operation
when connected to MongoDB >= 3.4.
.. versionadded:: 3.0
.. _createIndexes: https://docs.mongodb.com/manual/reference/command/createIndexes/'
| def create_indexes(self, indexes):
| if (not isinstance(indexes, list)):
raise TypeError('indexes must be a list')
names = []
def gen_indexes():
for index in indexes:
if (not isinstance(index, IndexModel)):
raise TypeError(('%r is not an instance of pymongo.operations.IndexModel' % (index,)))
document = index.document
names.append(document['name'])
(yield document)
cmd = SON([('createIndexes', self.name), ('indexes', list(gen_indexes()))])
with self._socket_for_writes() as sock_info:
self._command(sock_info, cmd, read_preference=ReadPreference.PRIMARY, codec_options=_UNICODE_REPLACE_CODEC_OPTIONS, write_concern=self.write_concern, parse_write_concern_error=True)
return names
|
'Internal create index helper.
:Parameters:
- `keys`: a list of tuples [(key, type), (key, type), ...]
- `index_options`: a dict of index options.'
| def __create_index(self, keys, index_options):
| index_doc = helpers._index_document(keys)
index = {'key': index_doc}
collation = validate_collation_or_none(index_options.pop('collation', None))
index.update(index_options)
with self._socket_for_writes() as sock_info:
if (collation is not None):
if (sock_info.max_wire_version < 5):
raise ConfigurationError('Must be connected to MongoDB 3.4+ to use collations.')
else:
index['collation'] = collation
cmd = SON([('createIndexes', self.name), ('indexes', [index])])
try:
self._command(sock_info, cmd, read_preference=ReadPreference.PRIMARY, codec_options=_UNICODE_REPLACE_CODEC_OPTIONS, write_concern=self.write_concern, parse_write_concern_error=True)
except OperationFailure as exc:
if (exc.code in common.COMMAND_NOT_FOUND_CODES):
index['ns'] = self.__full_name
wcn = (self.write_concern if self.write_concern.acknowledged else WriteConcern())
self.__database.system.indexes._insert(sock_info, index, True, False, False, wcn)
else:
raise
|
'Creates an index on this collection.
Takes either a single key or a list of (key, direction) pairs.
The key(s) must be an instance of :class:`basestring`
(:class:`str` in python 3), and the direction(s) must be one of
(:data:`~pymongo.ASCENDING`, :data:`~pymongo.DESCENDING`,
:data:`~pymongo.GEO2D`, :data:`~pymongo.GEOHAYSTACK`,
:data:`~pymongo.GEOSPHERE`, :data:`~pymongo.HASHED`,
:data:`~pymongo.TEXT`).
To create a single key ascending index on the key ``\'mike\'`` we just
use a string argument::
>>> my_collection.create_index("mike")
For a compound index on ``\'mike\'`` descending and ``\'eliot\'``
ascending we need to use a list of tuples::
>>> my_collection.create_index([("mike", pymongo.DESCENDING),
... ("eliot", pymongo.ASCENDING)])
All optional index creation parameters should be passed as
keyword arguments to this method. For example::
>>> my_collection.create_index([("mike", pymongo.DESCENDING)],
... background=True)
Valid options include, but are not limited to:
- `name`: custom name to use for this index - if none is
given, a name will be generated.
- `unique`: if ``True`` creates a uniqueness constraint on the index.
- `background`: if ``True`` this index should be created in the
background.
- `sparse`: if ``True``, omit from the index any documents that lack
the indexed field.
- `bucketSize`: for use with geoHaystack indexes.
Number of documents to group together within a certain proximity
to a given longitude and latitude.
- `min`: minimum value for keys in a :data:`~pymongo.GEO2D`
index.
- `max`: maximum value for keys in a :data:`~pymongo.GEO2D`
index.
- `expireAfterSeconds`: <int> Used to create an expiring (TTL)
collection. MongoDB will automatically delete documents from
this collection after <int> seconds. The indexed field must
be a UTC datetime or the data will not expire.
- `partialFilterExpression`: A document that specifies a filter for
a partial index.
- `collation` (optional): An instance of
:class:`~pymongo.collation.Collation`. This option is only supported
on MongoDB 3.4 and above.
See the MongoDB documentation for a full list of supported options by
server version.
.. warning:: `dropDups` is not supported by MongoDB 3.0 or newer. The
option is silently ignored by the server and unique index builds
using the option will fail if a duplicate value is detected.
.. note:: `partialFilterExpression` requires server version **>= 3.2**
.. note:: The :attr:`~pymongo.collection.Collection.write_concern` of
this collection is automatically applied to this operation when using
MongoDB >= 3.4.
:Parameters:
- `keys`: a single key or a list of (key, direction)
pairs specifying the index to create
- `**kwargs` (optional): any additional index creation
options (see the above list) should be passed as keyword
arguments
.. versionchanged:: 3.4
Apply this collection\'s write concern automatically to this operation
when connected to MongoDB >= 3.4. Support the `collation` option.
.. versionchanged:: 3.2
Added partialFilterExpression to support partial indexes.
.. versionchanged:: 3.0
Renamed `key_or_list` to `keys`. Removed the `cache_for` option.
:meth:`create_index` no longer caches index names. Removed support
for the drop_dups and bucket_size aliases.
.. mongodoc:: indexes'
| def create_index(self, keys, **kwargs):
| keys = helpers._index_list(keys)
name = kwargs.setdefault('name', helpers._gen_index_name(keys))
self.__create_index(keys, kwargs)
return name
|
'**DEPRECATED** - Ensures that an index exists on this collection.
.. versionchanged:: 3.0
**DEPRECATED**'
| def ensure_index(self, key_or_list, cache_for=300, **kwargs):
| warnings.warn('ensure_index is deprecated. Use create_index instead.', DeprecationWarning, stacklevel=2)
if (not (isinstance(cache_for, integer_types) or isinstance(cache_for, float))):
raise TypeError('cache_for must be an integer or float.')
if ('drop_dups' in kwargs):
kwargs['dropDups'] = kwargs.pop('drop_dups')
if ('bucket_size' in kwargs):
kwargs['bucketSize'] = kwargs.pop('bucket_size')
keys = helpers._index_list(key_or_list)
name = kwargs.setdefault('name', helpers._gen_index_name(keys))
if (not self.__database.client._cached(self.__database.name, self.__name, name)):
self.__create_index(keys, kwargs)
self.__database.client._cache_index(self.__database.name, self.__name, name, cache_for)
return name
return None
|
'Drops all indexes on this collection.
Can be used on non-existant collections or collections with no indexes.
Raises OperationFailure on an error.
.. note:: The :attr:`~pymongo.collection.Collection.write_concern` of
this collection is automatically applied to this operation when using
MongoDB >= 3.4.
.. versionchanged:: 3.4
Apply this collection\'s write concern automatically to this operation
when connected to MongoDB >= 3.4.'
| def drop_indexes(self):
| self.__database.client._purge_index(self.__database.name, self.__name)
self.drop_index('*')
|
'Drops the specified index on this collection.
Can be used on non-existant collections or collections with no
indexes. Raises OperationFailure on an error (e.g. trying to
drop an index that does not exist). `index_or_name`
can be either an index name (as returned by `create_index`),
or an index specifier (as passed to `create_index`). An index
specifier should be a list of (key, direction) pairs. Raises
TypeError if index is not an instance of (str, unicode, list).
.. warning::
if a custom name was used on index creation (by
passing the `name` parameter to :meth:`create_index` or
:meth:`ensure_index`) the index **must** be dropped by name.
:Parameters:
- `index_or_name`: index (or name of index) to drop
.. note:: The :attr:`~pymongo.collection.Collection.write_concern` of
this collection is automatically applied to this operation when using
MongoDB >= 3.4.
.. versionchanged:: 3.4
Apply this collection\'s write concern automatically to this operation
when connected to MongoDB >= 3.4.'
| def drop_index(self, index_or_name):
| name = index_or_name
if isinstance(index_or_name, list):
name = helpers._gen_index_name(index_or_name)
if (not isinstance(name, string_type)):
raise TypeError('index_or_name must be an index name or list')
self.__database.client._purge_index(self.__database.name, self.__name, name)
cmd = SON([('dropIndexes', self.__name), ('index', name)])
with self._socket_for_writes() as sock_info:
self._command(sock_info, cmd, read_preference=ReadPreference.PRIMARY, allowable_errors=['ns not found'], write_concern=self.write_concern, parse_write_concern_error=True)
|
'Rebuilds all indexes on this collection.
.. warning:: reindex blocks all other operations (indexes
are built in the foreground) and will be slow for large
collections.
.. versionchanged:: 3.4
Apply this collection\'s write concern automatically to this operation
when connected to MongoDB >= 3.4.
.. versionchanged:: 3.5
We no longer apply this collection\'s write concern to this operation.
MongoDB 3.4 silently ignored the write concern. MongoDB 3.6+ returns
an error if we include the write concern.'
| def reindex(self):
| cmd = SON([('reIndex', self.__name)])
with self._socket_for_writes() as sock_info:
return self._command(sock_info, cmd, read_preference=ReadPreference.PRIMARY, parse_write_concern_error=True)
|
'Get a cursor over the index documents for this collection.
>>> for index in db.test.list_indexes():
... print(index)
SON([(u\'v\', 1), (u\'key\', SON([(u\'_id\', 1)])),
(u\'name\', u\'_id_\'), (u\'ns\', u\'test.test\')])
:Returns:
An instance of :class:`~pymongo.command_cursor.CommandCursor`.
.. versionadded:: 3.0'
| def list_indexes(self):
| codec_options = CodecOptions(SON)
coll = self.with_options(codec_options)
with self._socket_for_primary_reads() as (sock_info, slave_ok):
cmd = SON([('listIndexes', self.__name), ('cursor', {})])
if (sock_info.max_wire_version > 2):
try:
cursor = self._command(sock_info, cmd, slave_ok, ReadPreference.PRIMARY, codec_options)['cursor']
except OperationFailure as exc:
if (exc.code != 26):
raise
cursor = {'id': 0, 'firstBatch': []}
return CommandCursor(coll, cursor, sock_info.address)
else:
namespace = (_UJOIN % (self.__database.name, 'system.indexes'))
res = helpers._first_batch(sock_info, self.__database.name, 'system.indexes', {'ns': self.__full_name}, 0, slave_ok, codec_options, ReadPreference.PRIMARY, cmd, self.database.client._event_listeners)
data = res['data']
cursor = {'id': res['cursor_id'], 'firstBatch': data, 'ns': namespace}
return CommandCursor(coll, cursor, sock_info.address, len(data))
|
'Get information on this collection\'s indexes.
Returns a dictionary where the keys are index names (as
returned by create_index()) and the values are dictionaries
containing information about each index. The dictionary is
guaranteed to contain at least a single key, ``"key"`` which
is a list of (key, direction) pairs specifying the index (as
passed to create_index()). It will also contain any other
metadata about the indexes, except for the ``"ns"`` and
``"name"`` keys, which are cleaned. Example output might look
like this:
>>> db.test.create_index("x", unique=True)
u\'x_1\'
>>> db.test.index_information()
{u\'_id_\': {u\'key\': [(u\'_id\', 1)]},
u\'x_1\': {u\'unique\': True, u\'key\': [(u\'x\', 1)]}}'
| def index_information(self):
| cursor = self.list_indexes()
info = {}
for index in cursor:
index['key'] = index['key'].items()
index = dict(index)
info[index.pop('name')] = index
return info
|
'Get the options set on this collection.
Returns a dictionary of options and their values - see
:meth:`~pymongo.database.Database.create_collection` for more
information on the possible options. Returns an empty
dictionary if the collection has not been created yet.'
| def options(self):
| with self._socket_for_primary_reads() as (sock_info, slave_ok):
if (sock_info.max_wire_version > 2):
criteria = {'name': self.__name}
else:
criteria = {'name': self.__full_name}
cursor = self.__database._list_collections(sock_info, slave_ok, criteria)
result = None
for doc in cursor:
result = doc
break
if (not result):
return {}
options = result.get('options', {})
if ('create' in options):
del options['create']
return options
|
'Perform an aggregation using the aggregation framework on this
collection.
All optional aggregate parameters should be passed as keyword arguments
to this method. Valid options include, but are not limited to:
- `allowDiskUse` (bool): Enables writing to temporary files. When set
to True, aggregation stages can write data to the _tmp subdirectory
of the --dbpath directory. The default is False.
- `maxTimeMS` (int): The maximum amount of time to allow the operation
to run in milliseconds.
- `batchSize` (int): The maximum number of documents to return per
batch. Ignored if the connected mongod or mongos does not support
returning aggregate results using a cursor, or `useCursor` is
``False``.
- `useCursor` (bool): Requests that the `server` provide results
using a cursor, if possible. Ignored if the connected mongod or
mongos does not support returning aggregate results using a cursor.
The default is ``True``. Set this to ``False`` when upgrading a 2.4
or older sharded cluster to 2.6 or newer (see the warning below).
- `collation` (optional): An instance of
:class:`~pymongo.collation.Collation`. This option is only supported
on MongoDB 3.4 and above.
The :meth:`aggregate` method obeys the :attr:`read_preference` of this
:class:`Collection`. Please note that using the ``$out`` pipeline stage
requires a read preference of
:attr:`~pymongo.read_preferences.ReadPreference.PRIMARY` (the default).
The server will raise an error if the ``$out`` pipeline stage is used
with any other read preference.
.. warning:: When upgrading a 2.4 or older sharded cluster to 2.6 or
newer the `useCursor` option **must** be set to ``False``
until all shards have been upgraded to 2.6 or newer.
.. note:: This method does not support the \'explain\' option. Please
use :meth:`~pymongo.database.Database.command` instead. An
example is included in the :ref:`aggregate-examples` documentation.
.. note:: The :attr:`~pymongo.collection.Collection.write_concern` of
this collection is automatically applied to this operation when using
MongoDB >= 3.4.
:Parameters:
- `pipeline`: a list of aggregation pipeline stages
- `**kwargs` (optional): See list of options above.
:Returns:
A :class:`~pymongo.command_cursor.CommandCursor` over the result
set.
.. versionchanged:: 3.4
Apply this collection\'s write concern automatically to this operation
when connected to MongoDB >= 3.4. Support the `collation` option.
.. versionchanged:: 3.0
The :meth:`aggregate` method always returns a CommandCursor. The
pipeline argument must be a list.
.. versionchanged:: 2.7
When the cursor option is used, return
:class:`~pymongo.command_cursor.CommandCursor` instead of
:class:`~pymongo.cursor.Cursor`.
.. versionchanged:: 2.6
Added cursor support.
.. versionadded:: 2.3
.. seealso:: :doc:`/examples/aggregation`
.. _aggregate command:
http://docs.mongodb.org/manual/applications/aggregation'
| def aggregate(self, pipeline, **kwargs):
| if (not isinstance(pipeline, list)):
raise TypeError('pipeline must be a list')
if ('explain' in kwargs):
raise ConfigurationError('The explain option is not supported. Use Database.command instead.')
collation = validate_collation_or_none(kwargs.pop('collation', None))
cmd = SON([('aggregate', self.__name), ('pipeline', pipeline)])
batch_size = common.validate_positive_integer_or_none('batchSize', kwargs.pop('batchSize', None))
use_cursor = common.validate_boolean('useCursor', kwargs.pop('useCursor', True))
with self._socket_for_reads() as (sock_info, slave_ok):
if (sock_info.max_wire_version > 0):
if use_cursor:
if ('cursor' not in kwargs):
kwargs['cursor'] = {}
if (batch_size is not None):
kwargs['cursor']['batchSize'] = batch_size
dollar_out = (pipeline and ('$out' in pipeline[(-1)]))
if ((sock_info.max_wire_version >= 5) and dollar_out and self.write_concern):
cmd['writeConcern'] = self.write_concern.document
cmd.update(kwargs)
if ((sock_info.max_wire_version >= 4) and ('readConcern' not in cmd)):
if dollar_out:
result = self._command(sock_info, cmd, slave_ok, parse_write_concern_error=True, collation=collation)
else:
result = self._command(sock_info, cmd, slave_ok, read_concern=self.read_concern, collation=collation)
else:
result = self._command(sock_info, cmd, slave_ok, parse_write_concern_error=dollar_out, collation=collation)
if ('cursor' in result):
cursor = result['cursor']
else:
cursor = {'id': 0, 'firstBatch': result['result'], 'ns': self.full_name}
return CommandCursor(self, cursor, sock_info.address).batch_size((batch_size or 0))
|
'Perform a query similar to an SQL *group by* operation.
**DEPRECATED** - The group command was deprecated in MongoDB 3.4. The
:meth:`~group` method is deprecated and will be removed in PyMongo 4.0.
Use :meth:`~aggregate` with the `$group` stage or :meth:`~map_reduce`
instead.
.. versionchanged:: 3.5
Deprecated the group method.
.. versionchanged:: 3.4
Added the `collation` option.
.. versionchanged:: 2.2
Removed deprecated argument: command'
| def group(self, key, condition, initial, reduce, finalize=None, **kwargs):
| warnings.warn('The group method is deprecated and will be removed in PyMongo 4.0. Use the aggregate method with the $group stage or the map_reduce method instead.', DeprecationWarning, stacklevel=2)
group = {}
if isinstance(key, string_type):
group['$keyf'] = Code(key)
elif (key is not None):
group = {'key': helpers._fields_list_to_dict(key, 'key')}
group['ns'] = self.__name
group['$reduce'] = Code(reduce)
group['cond'] = condition
group['initial'] = initial
if (finalize is not None):
group['finalize'] = Code(finalize)
cmd = SON([('group', group)])
collation = validate_collation_or_none(kwargs.pop('collation', None))
cmd.update(kwargs)
with self._socket_for_reads() as (sock_info, slave_ok):
return self._command(sock_info, cmd, slave_ok, collation=collation)['retval']
|
'Rename this collection.
If operating in auth mode, client must be authorized as an
admin to perform this operation. Raises :class:`TypeError` if
`new_name` is not an instance of :class:`basestring`
(:class:`str` in python 3). Raises :class:`~pymongo.errors.InvalidName`
if `new_name` is not a valid collection name.
:Parameters:
- `new_name`: new name for this collection
- `**kwargs` (optional): additional arguments to the rename command
may be passed as keyword arguments to this helper method
(i.e. ``dropTarget=True``)
.. note:: The :attr:`~pymongo.collection.Collection.write_concern` of
this collection is automatically applied to this operation when using
MongoDB >= 3.4.
.. versionchanged:: 3.4
Apply this collection\'s write concern automatically to this operation
when connected to MongoDB >= 3.4.'
| def rename(self, new_name, **kwargs):
| if (not isinstance(new_name, string_type)):
raise TypeError(('new_name must be an instance of %s' % (string_type.__name__,)))
if ((not new_name) or ('..' in new_name)):
raise InvalidName('collection names cannot be empty')
if ((new_name[0] == '.') or (new_name[(-1)] == '.')):
raise InvalidName("collecion names must not start or end with '.'")
if (('$' in new_name) and (not new_name.startswith('oplog.$main'))):
raise InvalidName("collection names must not contain '$'")
new_name = ('%s.%s' % (self.__database.name, new_name))
cmd = SON([('renameCollection', self.__full_name), ('to', new_name)])
with self._socket_for_writes() as sock_info:
if ((sock_info.max_wire_version >= 5) and self.write_concern):
cmd['writeConcern'] = self.write_concern.document
cmd.update(kwargs)
sock_info.command('admin', cmd, parse_write_concern_error=True)
|
'Get a list of distinct values for `key` among all documents
in this collection.
Raises :class:`TypeError` if `key` is not an instance of
:class:`basestring` (:class:`str` in python 3).
All optional distinct parameters should be passed as keyword arguments
to this method. Valid options include:
- `maxTimeMS` (int): The maximum amount of time to allow the count
command to run, in milliseconds.
- `collation` (optional): An instance of
:class:`~pymongo.collation.Collation`. This option is only supported
on MongoDB 3.4 and above.
The :meth:`distinct` method obeys the :attr:`read_preference` of
this :class:`Collection`.
:Parameters:
- `key`: name of the field for which we want to get the distinct
values
- `filter` (optional): A query document that specifies the documents
from which to retrieve the distinct values.
- `**kwargs` (optional): See list of options above.
.. versionchanged:: 3.4
Support the `collation` option.'
| def distinct(self, key, filter=None, **kwargs):
| if (not isinstance(key, string_type)):
raise TypeError(('key must be an instance of %s' % (string_type.__name__,)))
cmd = SON([('distinct', self.__name), ('key', key)])
if (filter is not None):
if ('query' in kwargs):
raise ConfigurationError("can't pass both filter and query")
kwargs['query'] = filter
collation = validate_collation_or_none(kwargs.pop('collation', None))
cmd.update(kwargs)
with self._socket_for_reads() as (sock_info, slave_ok):
return self._command(sock_info, cmd, slave_ok, read_concern=self.read_concern, collation=collation)['values']
|
'Perform a map/reduce operation on this collection.
If `full_response` is ``False`` (default) returns a
:class:`~pymongo.collection.Collection` instance containing
the results of the operation. Otherwise, returns the full
response from the server to the `map reduce command`_.
:Parameters:
- `map`: map function (as a JavaScript string)
- `reduce`: reduce function (as a JavaScript string)
- `out`: output collection name or `out object` (dict). See
the `map reduce command`_ documentation for available options.
Note: `out` options are order sensitive. :class:`~bson.son.SON`
can be used to specify multiple options.
e.g. SON([(\'replace\', <collection name>), (\'db\', <database name>)])
- `full_response` (optional): if ``True``, return full response to
this command - otherwise just return the result collection
- `**kwargs` (optional): additional arguments to the
`map reduce command`_ may be passed as keyword arguments to this
helper method, e.g.::
>>> db.test.map_reduce(map, reduce, "myresults", limit=2)
.. note:: The :meth:`map_reduce` method does **not** obey the
:attr:`read_preference` of this :class:`Collection`. To run
mapReduce on a secondary use the :meth:`inline_map_reduce` method
instead.
.. note:: The :attr:`~pymongo.collection.Collection.write_concern` of
this collection is automatically applied to this operation (if the
output is not inline) when using MongoDB >= 3.4.
.. versionchanged:: 3.4
Apply this collection\'s write concern automatically to this operation
when connected to MongoDB >= 3.4.
.. seealso:: :doc:`/examples/aggregation`
.. versionchanged:: 3.4
Added the `collation` option.
.. versionchanged:: 2.2
Removed deprecated arguments: merge_output and reduce_output
.. _map reduce command: http://docs.mongodb.org/manual/reference/command/mapReduce/
.. mongodoc:: mapreduce'
| def map_reduce(self, map, reduce, out, full_response=False, **kwargs):
| if (not isinstance(out, (string_type, collections.Mapping))):
raise TypeError(("'out' must be an instance of %s or a mapping" % (string_type.__name__,)))
cmd = SON([('mapreduce', self.__name), ('map', map), ('reduce', reduce), ('out', out)])
collation = validate_collation_or_none(kwargs.pop('collation', None))
cmd.update(kwargs)
inline = ('inline' in cmd['out'])
with self._socket_for_primary_reads() as (sock_info, slave_ok):
if ((sock_info.max_wire_version >= 5) and self.write_concern and (not inline)):
cmd['writeConcern'] = self.write_concern.document
cmd.update(kwargs)
if ((sock_info.max_wire_version >= 4) and ('readConcern' not in cmd) and inline):
response = self._command(sock_info, cmd, slave_ok, ReadPreference.PRIMARY, read_concern=self.read_concern, collation=collation)
else:
response = self._command(sock_info, cmd, slave_ok, ReadPreference.PRIMARY, parse_write_concern_error=(not inline), collation=collation)
if (full_response or (not response.get('result'))):
return response
elif isinstance(response['result'], dict):
dbase = response['result']['db']
coll = response['result']['collection']
return self.__database.client[dbase][coll]
else:
return self.__database[response['result']]
|
'Perform an inline map/reduce operation on this collection.
Perform the map/reduce operation on the server in RAM. A result
collection is not created. The result set is returned as a list
of documents.
If `full_response` is ``False`` (default) returns the
result documents in a list. Otherwise, returns the full
response from the server to the `map reduce command`_.
The :meth:`inline_map_reduce` method obeys the :attr:`read_preference`
of this :class:`Collection`.
:Parameters:
- `map`: map function (as a JavaScript string)
- `reduce`: reduce function (as a JavaScript string)
- `full_response` (optional): if ``True``, return full response to
this command - otherwise just return the result collection
- `**kwargs` (optional): additional arguments to the
`map reduce command`_ may be passed as keyword arguments to this
helper method, e.g.::
>>> db.test.inline_map_reduce(map, reduce, limit=2)
.. versionchanged:: 3.4
Added the `collation` option.'
| def inline_map_reduce(self, map, reduce, full_response=False, **kwargs):
| cmd = SON([('mapreduce', self.__name), ('map', map), ('reduce', reduce), ('out', {'inline': 1})])
collation = validate_collation_or_none(kwargs.pop('collation', None))
cmd.update(kwargs)
with self._socket_for_reads() as (sock_info, slave_ok):
if ((sock_info.max_wire_version >= 4) and ('readConcern' not in cmd)):
res = self._command(sock_info, cmd, slave_ok, read_concern=self.read_concern, collation=collation)
else:
res = self._command(sock_info, cmd, slave_ok, collation=collation)
if full_response:
return res
else:
return res.get('results')
|
'Internal findAndModify helper.'
| def __find_and_modify(self, filter, projection, sort, upsert=None, return_document=ReturnDocument.BEFORE, **kwargs):
| common.validate_is_mapping('filter', filter)
if (not isinstance(return_document, bool)):
raise ValueError('return_document must be ReturnDocument.BEFORE or ReturnDocument.AFTER')
collation = validate_collation_or_none(kwargs.pop('collation', None))
cmd = SON([('findAndModify', self.__name), ('query', filter), ('new', return_document)])
cmd.update(kwargs)
if (projection is not None):
cmd['fields'] = helpers._fields_list_to_dict(projection, 'projection')
if (sort is not None):
cmd['sort'] = helpers._index_document(sort)
if (upsert is not None):
common.validate_boolean('upsert', upsert)
cmd['upsert'] = upsert
with self._socket_for_writes() as sock_info:
if ((sock_info.max_wire_version >= 4) and ('writeConcern' not in cmd)):
wc_doc = self.write_concern.document
if wc_doc:
cmd['writeConcern'] = wc_doc
out = self._command(sock_info, cmd, read_preference=ReadPreference.PRIMARY, allowable_errors=[_NO_OBJ_ERROR], collation=collation)
_check_write_command_response([(0, out)])
return out.get('value')
|
'Finds a single document and deletes it, returning the document.
>>> db.test.count({\'x\': 1})
2
>>> db.test.find_one_and_delete({\'x\': 1})
{u\'x\': 1, u\'_id\': ObjectId(\'54f4e12bfba5220aa4d6dee8\')}
>>> db.test.count({\'x\': 1})
1
If multiple documents match *filter*, a *sort* can be applied.
>>> for doc in db.test.find({\'x\': 1}):
... print(doc)
{u\'x\': 1, u\'_id\': 0}
{u\'x\': 1, u\'_id\': 1}
{u\'x\': 1, u\'_id\': 2}
>>> db.test.find_one_and_delete(
... {\'x\': 1}, sort=[(\'_id\', pymongo.DESCENDING)])
{u\'x\': 1, u\'_id\': 2}
The *projection* option can be used to limit the fields returned.
>>> db.test.find_one_and_delete({\'x\': 1}, projection={\'_id\': False})
{u\'x\': 1}
:Parameters:
- `filter`: A query that matches the document to delete.
- `projection` (optional): a list of field names that should be
returned in the result document or a mapping specifying the fields
to include or exclude. If `projection` is a list "_id" will
always be returned. Use a mapping to exclude fields from
the result (e.g. projection={\'_id\': False}).
- `sort` (optional): a list of (key, direction) pairs
specifying the sort order for the query. If multiple documents
match the query, they are sorted and the first is deleted.
- `**kwargs` (optional): additional command arguments can be passed
as keyword arguments (for example maxTimeMS can be used with
recent server versions).
.. versionchanged:: 3.2
Respects write concern.
.. warning:: Starting in PyMongo 3.2, this command uses the
:class:`~pymongo.write_concern.WriteConcern` of this
:class:`~pymongo.collection.Collection` when connected to MongoDB >=
3.2. Note that using an elevated write concern with this command may
be slower compared to using the default write concern.
.. versionchanged:: 3.4
Added the `collation` option.
.. versionadded:: 3.0'
| def find_one_and_delete(self, filter, projection=None, sort=None, **kwargs):
| kwargs['remove'] = True
return self.__find_and_modify(filter, projection, sort, **kwargs)
|
'Finds a single document and replaces it, returning either the
original or the replaced document.
The :meth:`find_one_and_replace` method differs from
:meth:`find_one_and_update` by replacing the document matched by
*filter*, rather than modifying the existing document.
>>> for doc in db.test.find({}):
... print(doc)
{u\'x\': 1, u\'_id\': 0}
{u\'x\': 1, u\'_id\': 1}
{u\'x\': 1, u\'_id\': 2}
>>> db.test.find_one_and_replace({\'x\': 1}, {\'y\': 1})
{u\'x\': 1, u\'_id\': 0}
>>> for doc in db.test.find({}):
... print(doc)
{u\'y\': 1, u\'_id\': 0}
{u\'x\': 1, u\'_id\': 1}
{u\'x\': 1, u\'_id\': 2}
:Parameters:
- `filter`: A query that matches the document to replace.
- `replacement`: The replacement document.
- `projection` (optional): A list of field names that should be
returned in the result document or a mapping specifying the fields
to include or exclude. If `projection` is a list "_id" will
always be returned. Use a mapping to exclude fields from
the result (e.g. projection={\'_id\': False}).
- `sort` (optional): a list of (key, direction) pairs
specifying the sort order for the query. If multiple documents
match the query, they are sorted and the first is replaced.
- `upsert` (optional): When ``True``, inserts a new document if no
document matches the query. Defaults to ``False``.
- `return_document`: If
:attr:`ReturnDocument.BEFORE` (the default),
returns the original document before it was replaced, or ``None``
if no document matches. If
:attr:`ReturnDocument.AFTER`, returns the replaced
or inserted document.
- `**kwargs` (optional): additional command arguments can be passed
as keyword arguments (for example maxTimeMS can be used with
recent server versions).
.. versionchanged:: 3.4
Added the `collation` option.
.. versionchanged:: 3.2
Respects write concern.
.. warning:: Starting in PyMongo 3.2, this command uses the
:class:`~pymongo.write_concern.WriteConcern` of this
:class:`~pymongo.collection.Collection` when connected to MongoDB >=
3.2. Note that using an elevated write concern with this command may
be slower compared to using the default write concern.
.. versionadded:: 3.0'
| def find_one_and_replace(self, filter, replacement, projection=None, sort=None, upsert=False, return_document=ReturnDocument.BEFORE, **kwargs):
| common.validate_ok_for_replace(replacement)
kwargs['update'] = replacement
return self.__find_and_modify(filter, projection, sort, upsert, return_document, **kwargs)
|
'Finds a single document and updates it, returning either the
original or the updated document.
>>> db.test.find_one_and_update(
... {\'_id\': 665}, {\'$inc\': {\'count\': 1}, \'$set\': {\'done\': True}})
{u\'_id\': 665, u\'done\': False, u\'count\': 25}}
By default :meth:`find_one_and_update` returns the original version of
the document before the update was applied. To return the updated
version of the document instead, use the *return_document* option.
>>> from pymongo import ReturnDocument
>>> db.example.find_one_and_update(
... {\'_id\': \'userid\'},
... {\'$inc\': {\'seq\': 1}},
... return_document=ReturnDocument.AFTER)
{u\'_id\': u\'userid\', u\'seq\': 1}
You can limit the fields returned with the *projection* option.
>>> db.example.find_one_and_update(
... {\'_id\': \'userid\'},
... {\'$inc\': {\'seq\': 1}},
... projection={\'seq\': True, \'_id\': False},
... return_document=ReturnDocument.AFTER)
{u\'seq\': 2}
The *upsert* option can be used to create the document if it doesn\'t
already exist.
>>> db.example.delete_many({}).deleted_count
1
>>> db.example.find_one_and_update(
... {\'_id\': \'userid\'},
... {\'$inc\': {\'seq\': 1}},
... projection={\'seq\': True, \'_id\': False},
... upsert=True,
... return_document=ReturnDocument.AFTER)
{u\'seq\': 1}
If multiple documents match *filter*, a *sort* can be applied.
>>> for doc in db.test.find({\'done\': True}):
... print(doc)
{u\'_id\': 665, u\'done\': True, u\'result\': {u\'count\': 26}}
{u\'_id\': 701, u\'done\': True, u\'result\': {u\'count\': 17}}
>>> db.test.find_one_and_update(
... {\'done\': True},
... {\'$set\': {\'final\': True}},
... sort=[(\'_id\', pymongo.DESCENDING)])
{u\'_id\': 701, u\'done\': True, u\'result\': {u\'count\': 17}}
:Parameters:
- `filter`: A query that matches the document to update.
- `update`: The update operations to apply.
- `projection` (optional): A list of field names that should be
returned in the result document or a mapping specifying the fields
to include or exclude. If `projection` is a list "_id" will
always be returned. Use a dict to exclude fields from
the result (e.g. projection={\'_id\': False}).
- `sort` (optional): a list of (key, direction) pairs
specifying the sort order for the query. If multiple documents
match the query, they are sorted and the first is updated.
- `upsert` (optional): When ``True``, inserts a new document if no
document matches the query. Defaults to ``False``.
- `return_document`: If
:attr:`ReturnDocument.BEFORE` (the default),
returns the original document before it was updated, or ``None``
if no document matches. If
:attr:`ReturnDocument.AFTER`, returns the updated
or inserted document.
- `**kwargs` (optional): additional command arguments can be passed
as keyword arguments (for example maxTimeMS can be used with
recent server versions).
.. versionchanged:: 3.4
Added the `collation` option.
.. versionchanged:: 3.2
Respects write concern.
.. warning:: Starting in PyMongo 3.2, this command uses the
:class:`~pymongo.write_concern.WriteConcern` of this
:class:`~pymongo.collection.Collection` when connected to MongoDB >=
3.2. Note that using an elevated write concern with this command may
be slower compared to using the default write concern.
.. versionadded:: 3.0'
| def find_one_and_update(self, filter, update, projection=None, sort=None, upsert=False, return_document=ReturnDocument.BEFORE, **kwargs):
| common.validate_ok_for_update(update)
kwargs['update'] = update
return self.__find_and_modify(filter, projection, sort, upsert, return_document, **kwargs)
|
'Save a document in this collection.
**DEPRECATED** - Use :meth:`insert_one` or :meth:`replace_one` instead.
.. versionchanged:: 3.0
Removed the `safe` parameter. Pass ``w=0`` for unacknowledged write
operations.'
| def save(self, to_save, manipulate=True, check_keys=True, **kwargs):
| warnings.warn('save is deprecated. Use insert_one or replace_one instead', DeprecationWarning, stacklevel=2)
common.validate_is_document_type('to_save', to_save)
write_concern = None
collation = validate_collation_or_none(kwargs.pop('collation', None))
if kwargs:
write_concern = WriteConcern(**kwargs)
with self._socket_for_writes() as sock_info:
if (not (isinstance(to_save, RawBSONDocument) or ('_id' in to_save))):
return self._insert(sock_info, to_save, True, check_keys, manipulate, write_concern)
else:
self._update(sock_info, {'_id': to_save['_id']}, to_save, True, check_keys, False, manipulate, write_concern, collation=collation)
return to_save.get('_id')
|
'Insert a document(s) into this collection.
**DEPRECATED** - Use :meth:`insert_one` or :meth:`insert_many` instead.
.. versionchanged:: 3.0
Removed the `safe` parameter. Pass ``w=0`` for unacknowledged write
operations.'
| def insert(self, doc_or_docs, manipulate=True, check_keys=True, continue_on_error=False, **kwargs):
| warnings.warn('insert is deprecated. Use insert_one or insert_many instead.', DeprecationWarning, stacklevel=2)
write_concern = None
if kwargs:
write_concern = WriteConcern(**kwargs)
with self._socket_for_writes() as sock_info:
return self._insert(sock_info, doc_or_docs, (not continue_on_error), check_keys, manipulate, write_concern)
|
'Update a document(s) in this collection.
**DEPRECATED** - Use :meth:`replace_one`, :meth:`update_one`, or
:meth:`update_many` instead.
.. versionchanged:: 3.0
Removed the `safe` parameter. Pass ``w=0`` for unacknowledged write
operations.'
| def update(self, spec, document, upsert=False, manipulate=False, multi=False, check_keys=True, **kwargs):
| warnings.warn('update is deprecated. Use replace_one, update_one or update_many instead.', DeprecationWarning, stacklevel=2)
common.validate_is_mapping('spec', spec)
common.validate_is_mapping('document', document)
if document:
first = next(iter(document))
if first.startswith('$'):
check_keys = False
write_concern = None
collation = validate_collation_or_none(kwargs.pop('collation', None))
if kwargs:
write_concern = WriteConcern(**kwargs)
with self._socket_for_writes() as sock_info:
return self._update(sock_info, spec, document, upsert, check_keys, multi, manipulate, write_concern, collation=collation)
|
'Remove a document(s) from this collection.
**DEPRECATED** - Use :meth:`delete_one` or :meth:`delete_many` instead.
.. versionchanged:: 3.0
Removed the `safe` parameter. Pass ``w=0`` for unacknowledged write
operations.'
| def remove(self, spec_or_id=None, multi=True, **kwargs):
| warnings.warn('remove is deprecated. Use delete_one or delete_many instead.', DeprecationWarning, stacklevel=2)
if (spec_or_id is None):
spec_or_id = {}
if (not isinstance(spec_or_id, collections.Mapping)):
spec_or_id = {'_id': spec_or_id}
write_concern = None
collation = validate_collation_or_none(kwargs.pop('collation', None))
if kwargs:
write_concern = WriteConcern(**kwargs)
with self._socket_for_writes() as sock_info:
return self._delete(sock_info, spec_or_id, multi, write_concern, collation=collation)
|
'Update and return an object.
**DEPRECATED** - Use :meth:`find_one_and_delete`,
:meth:`find_one_and_replace`, or :meth:`find_one_and_update` instead.'
| def find_and_modify(self, query={}, update=None, upsert=False, sort=None, full_response=False, manipulate=False, **kwargs):
| warnings.warn('find_and_modify is deprecated, use find_one_and_delete, find_one_and_replace, or find_one_and_update instead', DeprecationWarning, stacklevel=2)
if ((not update) and (not kwargs.get('remove', None))):
raise ValueError('Must either update or remove')
if (update and kwargs.get('remove', None)):
raise ValueError("Can't do both update and remove")
if query:
kwargs['query'] = query
if update:
kwargs['update'] = update
if upsert:
kwargs['upsert'] = upsert
if sort:
if isinstance(sort, list):
kwargs['sort'] = helpers._index_document(sort)
elif (isinstance(sort, _ORDERED_TYPES) or (isinstance(sort, dict) and (len(sort) == 1))):
warnings.warn('Passing mapping types for `sort` is deprecated, use a list of (key, direction) pairs instead', DeprecationWarning, stacklevel=2)
kwargs['sort'] = sort
else:
raise TypeError('sort must be a list of (key, direction) pairs, a dict of len 1, or an instance of SON or OrderedDict')
fields = kwargs.pop('fields', None)
if (fields is not None):
kwargs['fields'] = helpers._fields_list_to_dict(fields, 'fields')
collation = validate_collation_or_none(kwargs.pop('collation', None))
cmd = SON([('findAndModify', self.__name)])
cmd.update(kwargs)
with self._socket_for_writes() as sock_info:
if ((sock_info.max_wire_version >= 4) and ('writeConcern' not in cmd)):
wc_doc = self.write_concern.document
if wc_doc:
cmd['writeConcern'] = wc_doc
out = self._command(sock_info, cmd, read_preference=ReadPreference.PRIMARY, allowable_errors=[_NO_OBJ_ERROR], collation=collation)
_check_write_command_response([(0, out)])
if (not out['ok']):
if (out['errmsg'] == _NO_OBJ_ERROR):
return None
else:
raise ValueError(('Unexpected Error: %s' % (out,)))
if full_response:
return out
else:
document = out.get('value')
if manipulate:
document = self.__database._fix_outgoing(document, self)
return document
|
'This is only here so that some API misusages are easier to debug.'
| def __call__(self, *args, **kwargs):
| if ('.' not in self.__name):
raise TypeError(("'Collection' object is not callable. If you meant to call the '%s' method on a 'Database' object it is failing because no such method exists." % self.__name))
raise TypeError(("'Collection' object is not callable. If you meant to call the '%s' method on a 'Collection' object it is failing because no such method exists." % self.__name.split('.')[(-1)]))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.