API Reference¶
If you are looking for information on a specific function, class or method, this part of the documentation is for you.
Auth¶
Collection¶
-
class
mongokit.collection.
Collection
(*args, **kwargs)[source]¶ -
find
(*args, **kwargs)[source]¶ Query the database.
The spec 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 fields 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
TypeError
if any of the arguments are of improper type. Returns an instance ofCursor
corresponding to this query.Parameters: - spec (optional): a SON object specifying elements which must be present for a document to be included in the result set
- fields (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 fields is a list “_id” will always be returned. Use a dict to exclude fields from the result (e.g. fields={‘_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
- timeout (optional): if True (the default), any returned cursor is closed by the server after 10 minutes of inactivity. If set to False, the returned cursor will never time out on the server. Care should be taken to ensure that cursors with timeout turned off are properly closed.
- snapshot (optional): if True, snapshot mode will be used for this query. Snapshot mode assures no duplicates are returned, or objects missed, which were present at both the start and end of the query’s execution. For details, see the snapshot documentation.
- tailable (optional): the result of this find call will be a tailable cursor - tailable cursors aren’t closed when the last data is retrieved but are kept open and the cursors location marks the final document’s position. if more data is received iteration of the cursor will continue from the last document received. For details, see the tailable cursor documentation.
- sort (optional): a list of (key, direction) pairs
specifying the sort order for this query. See
sort()
for details. - max_scan (optional): limit the number of documents examined when performing the query
- as_class (optional): class to use for documents in the
query result (default is
document_class
) - slave_okay (optional): if True, allows this query to be run against a replica secondary.
- await_data (optional): if True, the server will block for some extra time before returning, waiting for more data to return. Ignored if tailable is False.
- partial (optional): if True, mongos will return partial results if some shards are down instead of returning an error.
- manipulate: (optional): If True (the default), apply any outgoing SON manipulators before returning.
- network_timeout (optional): specify a timeout to use for
this query, which will override the
MongoClient
-level default - read_preference (optional): The read preference for this query.
- tag_sets (optional): The tag sets for this query.
- secondary_acceptable_latency_ms (optional): Any replica-set member whose ping time is within secondary_acceptable_latency_ms of the nearest member may accept reads. Default 15 milliseconds. Ignored by mongos and must be configured on the command line. See the localThreshold option for more information.
Note
The manipulate parameter may default to False in a future release.
Note
The max_scan parameter requires server version >= 1.5.1
New in version 2.3: The tag_sets and secondary_acceptable_latency_ms parameters.
New in version 1.11+: The await_data, partial, and manipulate parameters.
New in version 1.8: The network_timeout parameter.
New in version 1.7: The sort, max_scan and as_class parameters.
Changed in version 1.7: The fields parameter can now be a dict or any iterable in addition to a list.
New in version 1.1: The tailable parameter.
- added by mongokit::
- wrap (optional): a class object used to wrap
documents in the query result
-
find_and_modify
(*args, **kwargs)[source]¶ Update and return an object.
This is a thin wrapper around the findAndModify command. The positional arguments are designed to match the first three arguments to
update()
however most options should be passed as named parameters. Either update or remove arguments are required, all others are optional.Returns either the object before or after modification based on new parameter. If no objects match the query and upsert is false, returns
None
. If upserting and new is false, returns{}
.If the full_response parameter is
True
, the return value will be the entire response object from the server, including the ‘ok’ and ‘lastErrorObject’ fields, rather than just the modified object. This is useful mainly because the ‘lastErrorObject’ document holds information about the command’s execution.Parameters: - query: filter for the update (default
{}
) - update: see second argument to
update()
(no default) - upsert: insert if object doesn’t exist (default
False
) - sort: a list of (key, direction) pairs specifying the sort
order for this query. See
sort()
for details. - full_response: return the entire response object from the
server (default
False
) - remove: remove rather than updating (default
False
) - new: return updated rather than original object
(default
False
) - fields: see second argument to
find()
(default all) - **kwargs: any other options the findAndModify command supports can be passed here.
Note
Requires server version >= 1.3.0
Changed in version 2.5: Added the optional full_response parameter
Changed in version 2.4: Deprecated the use of mapping types for the sort parameter
New in version 1.10.
- added by mongokit::
- wrap (optional): a class object used to wrap
documents in the query result
- query: filter for the update (default
-
Connection¶
-
class
mongokit.connection.
CallableMixin
[source]¶ brings the callable method to a Document. usefull for the connection’s register method
-
mongokit.connection.
MongoClient
¶ alias of
Connection
-
mongokit.connection.
MongoReplicaSetClient
¶ alias of
ReplicaSetConnection
Cursor¶
-
class
mongokit.connection.
CallableMixin
[source] brings the callable method to a Document. usefull for the connection’s register method
-
class
mongokit.connection.
Connection
(*args, **kwargs)[source]
-
mongokit.connection.
MongoClient
alias of
Connection
-
mongokit.connection.
MongoReplicaSetClient
alias of
ReplicaSetConnection
-
class
mongokit.connection.
ReplicaSetConnection
(*args, **kwargs)[source]
Database¶
Document¶
-
class
mongokit.document.
Document
(doc=None, gen_skel=True, collection=None, lang='en', fallback_lang='en')[source]¶ -
atomic_save
= False¶
-
fetch
(spec=None, *args, **kwargs)[source]¶ return all document which match the structure of the object fetch() takes the same arguments than the the pymongo.collection.find method.
The query is launch against the db and collection of the object.
-
fetch_one
(*args, **kwargs)[source]¶ return one document which match the structure of the object fetch_one() takes the same arguments than the the pymongo.collection.find method.
If multiple documents are found, raise a MultipleResultsFound exception. If no document is found, return None
The query is launch against the db and collection of the object.
-
find
(*args, **kwargs)[source]¶ Query the database.
The spec argument is a prototype document that all results must match. For example if self si called MyDoc:
>>> mydocs = db.test.MyDoc.find({"hello": "world"})
only matches documents that have a key “hello” with value “world”. Matches can have other keys in addition to “hello”. The fields 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.
mydocs is a cursor which yield MyDoc object instances.
See pymongo’s documentation for more details on arguments.
-
find_fulltext
(search, **kwargs)[source]¶ Executes a full-text search. Additional parameters may be passed as keyword arguments.
-
find_one
(*args, **kwargs)[source]¶ Get the first object found from the database.
See pymongo’s documentation for more details on arguments.
-
force_autorefs_current_db
= False¶
-
classmethod
generate_index
(collection)[source]¶ generate indexes from
indexes
class-attributesupports additional index-creation-keywords supported by pymongos
ensure_index
.
-
gridfs
= []¶
-
indexes
= []¶
-
migrate
(safe=True, _process_to_bson=True)[source]¶ migrate the document following the migration_handler rules
safe : if True perform a safe update (see pymongo documentation for more details
-
migration_handler
= None¶
-
one
(*args, **kwargs)[source]¶ one() act like find() but will raise a mongokit.MultipleResultsFound exception if there is more than one result.
If no document is found, one() returns None
-
reload
()[source]¶ allow to refresh the document, so after using update(), it could reload its value from the database.
Be careful : reload() will erase all unsaved values.
If no _id is set in the document, a KeyError is raised.
-
save
(uuid=False, validate=None, safe=True, *args, **kwargs)[source]¶ save the document into the db.
if uuid is True, a uuid4 will be automatically generated else, the bson.ObjectId will be used.
If validate is True, the validate method will be called before saving. Not that the validate method will be called before the uuid is generated.
save() follow the pymongo.collection.save arguments
-
skip_validation
= False¶
-
to_json_type
()[source]¶ convert all document field into json type and return the new converted object
-
type_field
= '_type'¶
-
use_autorefs
= False¶
-
Grid¶
-
class
mongokit.grid.
FS
(obj)[source]¶ -
get_version
(filename, version=-1, **kwargs)[source]¶ Get a file from GridFS by
"filename"
or metadata fields.Returns a version of the file in GridFS whose filename matches filename and whose metadata fields match the supplied keyword arguments, as an instance of
GridOut
.Version numbering is a convenience atop the GridFS API provided by MongoDB. If more than one file matches the query (either by filename alone, by metadata fields, or by a combination of both), then version
-1
will be the most recently uploaded matching file,-2
the second most recently uploaded, etc. Version0
will be the first version uploaded,1
the second version, etc. So if three versions have been uploaded, then version0
is the same as version-3
, version1
is the same as version-2
, and version2
is the same as version-1
.Raises
NoFile
if no such version of that file exists.An index on
{filename: 1, uploadDate: -1}
will automatically be created when this method is called the first time.Parameters: - filename:
"filename"
of the file to get, or None - version (optional): version of the file to get (defaults to -1, the most recent version uploaded)
- **kwargs (optional): find files by custom metadata.
Changed in version 1.11: filename defaults to None;
New in version 1.11: Accept keyword arguments to find files by custom metadata.
New in version 1.9.
- filename:
-
Helpers¶
-
class
mongokit.helpers.
DotCollapsedDict
(passed_dict, remove_under_type=False, reference=None)[source]¶ A special dictionary constructor that take a dict and provides a dot collapsed dict:
>>> DotCollapsedDict({'a':{'b':{'c':{'d':3}, 'e':5}, "g":2}, 'f':6}) {'a.b.c.d': 3, 'a.b.e': 5, 'a.g': 2, 'f': 6}
>>> DotCollapsedDict({'bla':{'foo':{unicode:{"bla":3}}, 'bar':'egg'}}) {'bla.foo.$unicode.bla': 3, 'bla.bar': "egg"}
>>> DotCollapsedDict({'bla':{'foo':{unicode:{"bla":3}}, 'bar':'egg'}}, remove_under_type=True) {'bla.foo':{}, 'bla.bar':unicode}
>>> dic = {'bar':{'foo':3}, 'bla':{'g':2, 'h':3}} >>> DotCollapsedDict(dic, reference={'bar.foo':None, 'bla':{'g':None, 'h':None}}) {'bar.foo':3, 'bla':{'g':2, 'h':3}}
-
class
mongokit.helpers.
DotExpandedDict
(key_to_list_mapping)[source]¶ A special dictionary constructor that takes a dictionary in which the keys may contain dots to specify inner dictionaries. It’s confusing, but this example should make sense.
>>> d = DotExpandedDict({'person.1.firstname': ['Simon'], 'person.1.lastname': ['Willison'], 'person.2.firstname': ['Adrian'], 'person.2.lastname': ['Holovaty']}) >>> d {'person': {'1': {'lastname': ['Willison'], 'firstname': ['Simon']}, '2': {'lastname': ['Holovaty'], 'firstname': ['Adrian']}}} >>> d['person'] {'1': {'lastname': ['Willison'], 'firstname': ['Simon']}, '2': {'lastname': ['Holovaty'], 'firstname': ['Adrian']}} >>> d['person']['1'] {'lastname': ['Willison'], 'firstname': ['Simon']}
# Gotcha: Results are unpredictable if the dots are “uneven”: >>> DotExpandedDict({‘c.1’: 2, ‘c.2’: 3, ‘c’: 1}) {‘c’: 1}
-
mongokit.helpers.
fromtimestamp
(epoch_date)[source]¶ convert a float since epoch to a datetime object
Master Slave Connection¶
Master-Slave integration with for MongoKit Andreas Jung, info@zopyx.com (same license as Mongokit)
Migration¶
Migration¶
Operators¶
Paginator¶
-
class
mongokit.paginator.
Paginator
(cursor, page=1, limit=10)[source]¶ Provides pagination on a Cursor object
Keyword arguments: cursor – Cursor of a returned query page – The page number requested limit – The number of items per page
Properties: items – Returns the paginated Cursor object is_paginated – Boolean value determining if the cursor has multiple pages start_index – int index of the first item on the requested page end_index – int index of the last item on the requested page current_page – int page number of the requested page previous_page– int page number of the previous page w.r.t. current requested page next_page – int page number of the next page w.r.t. current requested page has_next – True or False if the Cursor has a next page has_previous – True or False if the Cursor has a previous page page_range – list of page numbers num_pages – int of the number of pages count – int total number of items on the cursor
-
count
¶
-
current_page
¶
-
end_index
¶
-
has_next
¶
-
has_previous
¶
-
is_paginated
¶
-
items
¶
-
next_page
¶
-
num_pages
¶
-
page_range
¶
-
previous_page
¶
-
start_index
¶
-
Schema Document¶
-
class
mongokit.schema_document.
CustomType
[source]¶ -
init_type
= None¶
-
mongo_type
= None¶
-
python_type
= None¶
-
-
class
mongokit.schema_document.
DotCollapsedDict
(passed_dict, remove_under_type=False, reference=None)[source]¶ A special dictionary constructor that take a dict and provides a dot collapsed dict:
>>> DotCollapsedDict({'a':{'b':{'c':{'d':3}, 'e':5}, "g":2}, 'f':6}) {'a.b.c.d': 3, 'a.b.e': 5, 'a.g': 2, 'f': 6}
>>> DotCollapsedDict({'bla':{'foo':{unicode:{"bla":3}}, 'bar':'egg'}}) {'bla.foo.$unicode.bla': 3, 'bla.bar': "egg"}
>>> DotCollapsedDict({'bla':{'foo':{unicode:{"bla":3}}, 'bar':'egg'}}, remove_under_type=True) {'bla.foo':{}, 'bla.bar':unicode}
>>> dic = {'bar':{'foo':3}, 'bla':{'g':2, 'h':3}} >>> DotCollapsedDict(dic, reference={'bar.foo':None, 'bla':{'g':None, 'h':None}}) {'bar.foo':3, 'bla':{'g':2, 'h':3}}
-
class
mongokit.schema_document.
DotedDict
(doc=None, warning=False)[source]¶ Dot notation dictionary access
-
class
mongokit.schema_document.
DotExpandedDict
(key_to_list_mapping)[source]¶ A special dictionary constructor that takes a dictionary in which the keys may contain dots to specify inner dictionaries. It’s confusing, but this example should make sense.
>>> d = DotExpandedDict({'person.1.firstname': ['Simon'], 'person.1.lastname': ['Willison'], 'person.2.firstname': ['Adrian'], 'person.2.lastname': ['Holovaty']}) >>> d {'person': {'1': {'lastname': ['Willison'], 'firstname': ['Simon']}, '2': {'lastname': ['Holovaty'], 'firstname': ['Adrian']}}} >>> d['person'] {'1': {'lastname': ['Willison'], 'firstname': ['Simon']}, '2': {'lastname': ['Holovaty'], 'firstname': ['Adrian']}} >>> d['person']['1'] {'lastname': ['Willison'], 'firstname': ['Simon']}
# Gotcha: Results are unpredictable if the dots are “uneven”: >>> DotExpandedDict({‘c.1’: 2, ‘c.2’: 3, ‘c’: 1}) {‘c’: 1}
-
class
mongokit.schema_document.
i18n
(field_type=None, field_name=None)[source]¶ CustomType to deal with i18n
-
class
mongokit.schema_document.
SchemaDocument
(doc=None, gen_skel=True, _gen_auth_types=True, _validate=True, lang='en', fallback_lang='en')[source]¶ A SchemaDocument is dictionary with a building structured schema The validate method will check that the document match the underling structure. A structure must be specify in each SchemaDocument.
>>> class TestDoc(SchemaDocument): ... structure = { ... "foo":six.text_type, ... "bar":int, ... "nested":{ ... "bla":float}}
unicode, int, float are python types listed in mongokit.authorized_types.
>>> doc = TestDoc() >>> doc {'foo': None, 'bar': None, 'nested': {'bla': None}}
A SchemaDocument works just like dict:
>>> doc['bar'] = 3 >>> doc['foo'] = "test"
We can describe fields as required with the required attribute:
>>> TestDoc.required_fields = ['bar', 'nested.bla'] >>> doc = TestDoc() >>> doc['bar'] = 2
Validation is made with the validate() method:
>>> doc.validate() Traceback (most recent call last): ... RequireFieldError: nested.bla is required
Default values can be set by using the attribute default_values :
>>> TestDoc.default_values = {"bar":3, "nested.bla":2.0} >>> doc = TestDoc() >>> doc {'foo': None, 'bar': 3, 'nested': {'bla': 2.0}} >>> doc.validate()
Validators can be added in order to validate some values :
>>> TestDoc.validators = {"bar":lambda x: x>0, "nested.bla": lambda x: x<0} >>> doc = TestDoc() >>> doc['bar'] = 3 >>> doc['nested']['bla'] = 2.0 >>> doc.validate() Traceback (most recent call last): ... ValidationError: nested.bla does not pass the validator <lambda>
If you want to use the dot notation (ala json), you must set the use_dot_notation attribute to True:
>>> class TestDotNotation(SchemaDocument): ... structure = { ... "foo":{ "bar":unicode} ... } ... use_dot_notation=True
>>> doc = TestDotNotation() >>> doc.foo.bar = u"bla" >>> doc {"foo":{"bar":u"bla}}
-
default_values
= {}¶
-
dot_notation_warning
= False¶
-
generate_skeleton
()[source]¶ validate and generate the skeleton of the document from the structure (unknown values are set to None)
-
i18n
= []¶
-
raise_validation_errors
= True¶
-
required_fields
= []¶
-
skip_validation
= False¶
-
structure
= None¶
-
use_dot_notation
= False¶
-
use_schemaless
= False¶
-
validate
()[source]¶ validate the document.
- This method will verify if :
- the doc follow the structure,
- all required fields are filled
Additionally, this method will process all validators.
-
validators
= {}¶
-
Versioned Document¶
-
class
mongokit.versioned_document.
RevisionDocument
(doc=None, gen_skel=True, collection=None, lang='en', fallback_lang='en')[source]¶ -
structure
= {'id': <class 'str'>, 'revision': <class 'int'>, 'doc': <class 'dict'>}¶
-
-
class
mongokit.versioned_document.
VersionedDocument
(doc=None, *args, **kwargs)[source]¶ This object implement a vesionnized mongo document
-
delete
(versioning=False, *args, **kwargs)[source]¶ if versioning is True delete revisions documents as well
-