Djamo Collection Implementation

Documents by themselves does not have ability to save to database. To do that you should use a collection object. Its easy to use collections by subclassing the Collection base class.

See also

Since :py:class: ~djamo.collections.BaseCollection is a subclass of PyMongos Collection class, and we don’t document the methods that does not overridden, it will be heplful for you to take a look at PyMongo Collection document too.

BaseCollection class

This collection class is the base of other Djamo collections and contains the same interface as PyMongo.

class djamo.collections.BaseCollection(create=False, client=None, *args, **kwargs)

Djamo implementation of Mongodb collection.

class Operators

This class contains all the handlers of query specific operator of MongoDB.

bit_update(self, value, document, *args, **kwargs)

Handle the $bit operator for document update.

pop_update(self, value, document, *args, **kwargs)

Handle the $pop operator for document update.

BaseCollection._get_document(self)

Check the collection’s document and return it if it was a valid document

BaseCollection._prepare_data(self, doc_or_docs)

validate doc_or_docs and create a dictionary data.

BaseCollection._prepare_query(self, query_item, query_type='query')

Prepare each query_item (key, value) for the specific query type.

BaseCollection.document

Class that will be use as a document class for this collection. This class will be responsible for pickling and unpickling data to and from database.

alias of dict

BaseCollection.find(self, spec=None, fields=None, *args, **kwargs)

make queries on database and current collection.

The spec argument is a prototype document that all results must match. For example:

from .models import UserBaseCollection

collection = UserBaseCollection() collection.find({“username”: “Okarin”})

only matches documents that have a key “username” with value “Okarin”. Matches can have other keys in addition to “Okarin. 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.

Parameters:
  • spec – (optional) a SON object specifying elements which must be present for a document to be included in the result set.
  • 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, any returned cursor will be subject to the normal timeout behavior of the mongod process. Otherwise, the returned cursor will never timeout at 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 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.
Pram 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}).

BaseCollection.find_one(self, spec_or_id=None, *args, **kwargs)

Get a single document from the database. All arguments to find() are also valid arguments for find_one(), although any limit argument will be ignored. Returns a single document, or None if no matching document is found.

Parameters:spec_or_id – (optional) a dictionary specifying the query to be performed OR any other type to be used as the value for a query for “_id”.
BaseCollection.indexes = []

Index list for current collection, each element will be a index dictionary according to mongodb standards. Each element should be a list with index dictionary as its first element and index options as its second.

BaseCollection.insert(self, doc_or_docs, *args, **kwargs)

Insert a document(s) into current collection. and return the _id value (or list of _id values) of doc_or_docs or [None] if manipulate is False and the documents passed as doc_or_docs do not include an _id field.

Parameters:
  • doc_or_docs – a document or list of documents to be inserted.
  • manipulate – (optional): If True manipulate the documents before inserting.
  • check_keys – (optional): If True check if keys start with $ or contain ., raising InvalidName in either case
  • continue_on_error – (optional): If True, the database will not stop processing a bulk insert if one fails (e.g. due to duplicate IDs). This makes bulk insert behave similarly to a series of single inserts, except lastError will be set if any insert fails, not just the last one. If multiple errors occur, only the most recent will be reported by error().
  • w – (optional) (integer or string) If this is a replica set, write operations will block until they have been replicated to the specified number or tagged set of servers. w=<int> always includes the replica set primary (e.g. w=3 means write to the primary and wait until replicated to two secondaries). Passing w=0 disables write acknowledgement and all other write concern options.
  • wtimeout – (optional): (integer) Used in conjunction with w. Specify a value in milliseconds to control how long to wait for write propagation to complete. If replication does not complete in the given timeframe, a timeout exception is raised.
  • j – (optional): If True block until write operations have been committed to the journal. Ignored if the server is running without journaling.
  • fsync – (optional): If True force the database to fsync all files before returning. When used with j the server awaits the next group commit before returning.
BaseCollection.name = None

Specify the name of collection in database level. In case of a None value current collection class name will use in lower case

BaseCollection.prepare_query(self, query, query_type='query')

Prepare query (spec).

BaseCollection.remove(self, spec_or_id=None, *args, **kwargs)

Remove a document(s) from this collection. returns A document (dict) describing the effect of the remove or None if write acknowledgement is disabled.

If spec_or_id is None, all documents in this collection will be removed This is not equivalent to calling drop_collection(), however, as indexes will not be removed.

By default an acknowledgment is requested from the server that the remove was successful, raising OperationFailure if an error occurred. Passing w=0 disables write acknowledgement and all other write concern options.

Parameters:
  • spec_or_id – (optional): a dictionary specifying the documents to be removed OR any other type specifying the value of “_id” for the document to be removed
  • w – (optional): (integer or string) If this is a replica set, write operations will block until they have been replicated to the specified number or tagged set of servers. w=<int> always includes the replica set primary (e.g. w=3 means write to the primary and wait until replicated to two secondaries). Passing w=0 disables write acknowledgement and all other write concern options.
  • wtimeout – (optional) (integer) Used in conjunction with w. Specify a value in milliseconds to control how long to wait for write propagation to complete. If replication does not complete in the given timeframe, a timeout exception is raised.
  • j – (optional) If True block until write operations have been committed to the journal. Ignored if the server is running without journaling.
  • fsync – (optional) If True force the database to fsync all files before returning. When used with j the server awaits the next group commit before returning.
BaseCollection.save(self, to_save, *args, **kwargs)

save a document(s) into current collection. and return the _id value (or list of _id values) of doc_or_docs or [None] if manipulate is False and the documents passed as doc_or_docs do not include an _id field.

Parameters:
  • to_save – A document to be insert or update.
  • manipulate – (optional): If True manipulate the documents before inserting.
  • check_keys – (optional):If True check if keys start with $ or contain ., raising InvalidName in either case.
  • w – (optional) (integer or string) If this is a replica set, write operations will block until they have been replicated to the specified number or tagged set of servers. w=<int> always includes the replica set primary (e.g. w=3 means write to the primary and wait until replicated to two secondaries). Passing w=0 disables write acknowledgement and all other write concern options.
  • wtimeout – (optional): (integer) Used in conjunction with w. Specify a value in milliseconds to control how long to wait for write propagation to complete. If replication does not complete in the given timeframe, a timeout exception is raised.
  • j – (optional): If True block until write operations have been committed to the journal. Ignored if the server is running without journaling.
  • fsync – (optional): If True force the database to fsync all files before returning. When used with j the server awaits the next group commit before returning.
BaseCollection.update(self, spec, doc, *args, **kwargs)

Update a document(s) in this collection.

Parameters:
  • spec – A dict or SON instance specifying elements which must be present for a document to be updated
  • doc – A dict or SON instance specifying the document to be used for the update or (in the case of an upsert) insert - see docs on MongoDB update modifiers
  • upsert – (optional): perform an upsert if True
  • manipulate – (optional): If True manipulate the documents before inserting.
  • check_keys – (optional):If True check if keys start with $ or contain ., raising InvalidName in either case.
  • multi – (optional): update all documents that match spec, rather than just the first matching document. The default value for multi is currently False, but this might eventually change to True. It is recommended that you specify this argument explicitly for all update operations in order to prepare your code for that change.
  • w – (optional) (integer or string) If this is a replica set, write operations will block until they have been replicated to the specified number or tagged set of servers. w=<int> always includes the replica set primary (e.g. w=3 means write to the primary and wait until replicated to two secondaries). Passing w=0 disables write acknowledgement and all other write concern options.
  • wtimeout – (optional): (integer) Used in conjunction with w. Specify a value in milliseconds to control how long to wait for write propagation to complete. If replication does not complete in the given timeframe, a timeout exception is raised.
  • j – (optional): If True block until write operations have been committed to the journal. Ignored if the server is running without journaling.
  • fsync – (optional): If True force the database to fsync all files before returning. When used with j the server awaits the next group commit before returning.
BaseCollection.validate_document(self, doc)

Return a validated instance of the current collection document from provided doc parameter.

Parameters:doc – An instance of the current collection document or a dictionary like object.

Collection class

This class is contains all the methods that are wrappers to PyMongo interface or PyMongo did not provided.

class djamo.collections.Collection(create=False, client=None, *args, **kwargs)
update_all(self, spec, doc, *args, **kwargs)

Update all the documents which matched to spec.

Parameters:
  • spec – A dict or SON instance specifying elements which must be present for a document to be updated
  • doc – A dict or SON instance specifying the document to be used for the update or (in the case of an upsert) insert - see docs on MongoDB update modifiers

Table Of Contents

This Page