本文整理汇总了Python中pymongo.helpers._index_document方法的典型用法代码示例。如果您正苦于以下问题:Python helpers._index_document方法的具体用法?Python helpers._index_document怎么用?Python helpers._index_document使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pymongo.helpers
的用法示例。
在下文中一共展示了helpers._index_document方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: count
# 需要导入模块: from pymongo import helpers [as 别名]
# 或者: from pymongo.helpers import _index_document [as 别名]
def count(self, filter: Optional[dict] = None, hint: Optional[Union[str, List[Tuple]]] = None,
limit: Optional[int] = None, skip: Optional[int] = None, max_time_ms: Optional[int] = None,
comment: Union[str, dict] = None, collation: Optional[Collation]=None) -> int:
cmd = SON([('count', self.name)])
if filter is not None:
cmd['query'] = filter
if hint is not None:
if isinstance(hint, str):
cmd['hint'] = hint
else:
cmd['hint'] = helpers._index_document(hint)
if limit is not None:
cmd['limit'] = limit
if skip is not None:
cmd['skip'] = skip
if max_time_ms is not None:
cmd['maxTimeMS'] = max_time_ms
if comment is not None:
cmd['$comment'] = comment
collation = validate_collation_or_none(collation)
return await self._count(cmd, collation=collation)
示例2: hint
# 需要导入模块: from pymongo import helpers [as 别名]
# 或者: from pymongo.helpers import _index_document [as 别名]
def hint(self, index):
"""Adds a 'hint', telling Mongo the proper index to use for the query.
Judicious use of hints can greatly improve query
performance. When doing a query on multiple fields (at least
one of which is indexed) pass the indexed field as a hint to
the query. Hinting will not do anything if the corresponding
index does not exist. Raises
:class:`~pymongo.errors.InvalidOperation` if this cursor has
already been used.
`index` should be an index as passed to
:meth:`~pymongo.collection.Collection.create_index`
(e.g. ``[('field', ASCENDING)]``) or the name of the index.
If `index` is ``None`` any existing hint for this query is
cleared. The last hint applied to this cursor takes precedence
over all others.
:Parameters:
- `index`: index to hint on (as an index specifier)
.. versionchanged:: 2.8
The :meth:`~hint` method accepts the name of the index.
"""
self.__check_okay_to_chain()
if index is None:
self.__hint = None
return self
if isinstance(index, string_type):
self.__hint = index
else:
self.__hint = helpers._index_document(index)
return self
示例3: hint
# 需要导入模块: from pymongo import helpers [as 别名]
# 或者: from pymongo.helpers import _index_document [as 别名]
def hint(self, index):
"""Adds a 'hint', telling Mongo the proper index to use for the query.
Judicious use of hints can greatly improve query
performance. When doing a query on multiple fields (at least
one of which is indexed) pass the indexed field as a hint to
the query. Hinting will not do anything if the corresponding
index does not exist. Raises
:class:`~pymongo.errors.InvalidOperation` if this cursor has
already been used.
`index` should be an index as passed to
:meth:`~pymongo.collection.Collection.create_index`
(e.g. ``[('field', ASCENDING)]``). If `index`
is ``None`` any existing hints for this query are cleared. The
last hint applied to this cursor takes precedence over all
others.
:Parameters:
- `index`: index to hint on (as an index specifier)
"""
self.__check_okay_to_chain()
if index is None:
self.__hint = None
return self
self.__hint = helpers._index_document(index)
return self
示例4: hint
# 需要导入模块: from pymongo import helpers [as 别名]
# 或者: from pymongo.helpers import _index_document [as 别名]
def hint(self, index: Union[str, List[tuple]]) -> 'Cursor':
"""Adds a 'hint', telling Mongo the proper index to use for the query.
Judicious use of hints can greatly improve query
performance. When doing a query on multiple fields (at least
one of which is indexed) pass the indexed field as a hint to
the query. Hinting will not do anything if the corresponding
index does not exist. Raises
:class:`~pymongo.errors.InvalidOperation` if this cursor has
already been used.
`index` should be an index as passed to
:meth:`~aiomongo.collection.Collection.create_index`
(e.g. ``[('field', ASCENDING)]``) or the name of the index.
If `index` is ``None`` any existing hint for this query is
cleared. The last hint applied to this cursor takes precedence
over all others.
:Parameters:
- `index`: index to hint on (as an index specifier)
"""
self.__check_okay_to_chain()
if index is None:
self.__hint = None
return self
if isinstance(index, str):
self.__hint = index
else:
self.__hint = helpers._index_document(index)
return self
示例5: __find_and_modify
# 需要导入模块: from pymongo import helpers [as 别名]
# 或者: from pymongo.helpers import _index_document [as 别名]
def __find_and_modify(self, filter: dict, projection: Optional[Union[list, dict]],
sort: Optional[List[tuple]], upsert: Optional[bool] = None,
return_document: bool = ReturnDocument.BEFORE, **kwargs) -> MutableMapping:
"""Internal findAndModify helper."""
common.validate_is_mapping('filter', filter)
if not isinstance(return_document, bool):
raise ValueError('return_document must be ReturnDocument.BEFORE or ReturnDocument.AFTER')
cmd = SON([('findAndModify', self.name),
('query', filter),
('new', return_document)])
collation = validate_collation_or_none(kwargs.pop('collation', None))
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
connection = await self.database.client.get_connection()
if connection.max_wire_version >= 4 and 'writeConcern' not in cmd:
wc_doc = self.write_concern.document
if wc_doc:
cmd['writeConcern'] = wc_doc
out = await connection.command(
self.database.name, cmd, ReadPreference.PRIMARY, self.codec_options,
allowable_errors=[_NO_OBJ_ERROR], collation=collation
)
helpers._check_write_command_response([(0, out)])
return out.get('value')
示例6: sort
# 需要导入模块: from pymongo import helpers [as 别名]
# 或者: from pymongo.helpers import _index_document [as 别名]
def sort(self, key_or_list, direction=None):
"""Sorts this cursor's results.
Pass a field name and a direction, either
:data:`~pymongo.ASCENDING` or :data:`~pymongo.DESCENDING`::
for doc in collection.find().sort('field', pymongo.ASCENDING):
print(doc)
To sort by multiple fields, pass a list of (key, direction) pairs::
for doc in collection.find().sort([
('field1', pymongo.ASCENDING),
('field2', pymongo.DESCENDING)]):
print(doc)
Beginning with MongoDB version 2.6, text search results can be
sorted by relevance::
cursor = db.test.find(
{'$text': {'$search': 'some words'}},
{'score': {'$meta': 'textScore'}})
# Sort by 'score' field.
cursor.sort([('score', {'$meta': 'textScore'})])
for doc in cursor:
print(doc)
Raises :class:`~pymongo.errors.InvalidOperation` if this cursor has
already been used. Only the last :meth:`sort` applied to this
cursor has any effect.
:Parameters:
- `key_or_list`: a single key or a list of (key, direction)
pairs specifying the keys to sort on
- `direction` (optional): only used if `key_or_list` is a single
key, if not given :data:`~pymongo.ASCENDING` is assumed
"""
self.__check_okay_to_chain()
keys = helpers._index_list(key_or_list, direction)
self.__ordering = helpers._index_document(keys)
return self
示例7: __init__
# 需要导入模块: from pymongo import helpers [as 别名]
# 或者: from pymongo.helpers import _index_document [as 别名]
def __init__(self, keys, **kwargs):
"""Create an Index instance.
For use with :meth:`~pymongo.collection.Collection.create_indexes`.
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`).
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.
See the MongoDB documentation for a full list of supported options by
server version.
.. note:: `partialFilterExpression` requires server version **>= 3.2**
: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.2
Added partialFilterExpression to support partial indexes.
"""
keys = _index_list(keys)
if "name" not in kwargs:
kwargs["name"] = _gen_index_name(keys)
kwargs["key"] = _index_document(keys)
self.__document = kwargs
示例8: __init__
# 需要导入模块: from pymongo import helpers [as 别名]
# 或者: from pymongo.helpers import _index_document [as 别名]
def __init__(self, collection: 'aiomongo.Collection',
filter: Optional[dict] = None, projection: Optional[Union[dict, list]] = None,
skip: int = 0, limit: int = 0, sort: Optional[List[tuple]] = None,
modifiers: Optional[dict] = None, batch_size: int = 0, no_cursor_timeout: bool = False,
collation: Optional[Union[Collation, dict]]=None) -> None:
spec = filter
if spec is None:
spec = {}
validate_is_mapping('filter', spec)
if not isinstance(skip, int):
raise TypeError('skip must be an instance of int')
if not isinstance(limit, int):
raise TypeError('limit must be an instance of int')
if modifiers is not None:
validate_is_mapping('modifiers', modifiers)
if not isinstance(batch_size, int):
raise TypeError('batch_size must be an integer')
if batch_size < 0:
raise ValueError('batch_size must be >= 0')
if projection is not None:
if not projection:
projection = {'_id': 1}
projection = helpers._fields_list_to_dict(projection, 'projection')
self.__id = None
self.__codec_options = DEFAULT_CODEC_OPTIONS
self.__collation = validate_collation_or_none(collation)
self.__collection = collection
self.__connection = None
self.__data = deque()
self.__explain = False
self.__max_scan = None
self.__spec = spec
self.__projection = projection
self.__skip = skip
self.__limit = limit
self.__batch_size = batch_size
self.__modifiers = modifiers or {}
self.__ordering = sort and helpers._index_document(sort) or None
self.__hint = None
self.__comment = None
self.__max_time_ms = None
self.__max_await_time_ms = None
self.__max = None
self.__min = None
self.__killed = False
self.__codec_options = collection.codec_options
self.__read_preference = collection.read_preference
self.__read_concern = collection.read_concern
self.__retrieved = 0
self.__query_flags = 0
if self.__read_preference != ReadPreference.PRIMARY:
self.__query_flags |= _QUERY_OPTIONS['slave_okay']
if no_cursor_timeout:
self.__query_flags |= _QUERY_OPTIONS['no_timeout']
示例9: sort
# 需要导入模块: from pymongo import helpers [as 别名]
# 或者: from pymongo.helpers import _index_document [as 别名]
def sort(self, key_or_list: Union[str, List[tuple]], direction: Optional[int] = None) -> 'Cursor':
"""Sorts this cursor's results.
Pass a field name and a direction, either
:data:`~pymongo.ASCENDING` or :data:`~pymongo.DESCENDING`::
async for doc in collection.find().sort('field', pymongo.ASCENDING):
print(doc)
To sort by multiple fields, pass a list of (key, direction) pairs::
async for doc in collection.find().sort([
('field1', pymongo.ASCENDING),
('field2', pymongo.DESCENDING)]):
print(doc)
Beginning with MongoDB version 2.6, text search results can be
sorted by relevance::
cursor = db.test.find(
{'$text': {'$search': 'some words'}},
{'score': {'$meta': 'textScore'}})
# Sort by 'score' field.
cursor.sort([('score', {'$meta': 'textScore'})])
async for doc in cursor:
print(doc)
Raises :class:`~pymongo.errors.InvalidOperation` if this cursor has
already been used. Only the last :meth:`sort` applied to this
cursor has any effect.
:Parameters:
- `key_or_list`: a single key or a list of (key, direction)
pairs specifying the keys to sort on
- `direction` (optional): only used if `key_or_list` is a single
key, if not given :data:`~pymongo.ASCENDING` is assumed
"""
self.__check_okay_to_chain()
keys = helpers._index_list(key_or_list, direction)
self.__ordering = helpers._index_document(keys)
return self
示例10: __init__
# 需要导入模块: from pymongo import helpers [as 别名]
# 或者: from pymongo.helpers import _index_document [as 别名]
def __init__(self, keys, **kwargs):
"""Create an Index instance.
For use with :meth:`~pymongo.collection.Collection.create_indexes`.
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`).
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`: An instance of `~pymongo.collation.Collation` that
specifies the collation to use in MongoDB >= 3.4.
See the MongoDB documentation for a full list of supported options by
server version.
.. note:: `partialFilterExpression` requires server version **>= 3.2**
: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.2
Added partialFilterExpression to support partial indexes.
"""
keys = _index_list(keys)
if "name" not in kwargs:
kwargs["name"] = _gen_index_name(keys)
kwargs["key"] = _index_document(keys)
collation = validate_collation_or_none(kwargs.pop('collation', None))
self.__document = kwargs
if collation is not None:
self.__document['collation'] = collation