wiki:Notes/PythonMongoDB

Python MongoDB

See MongoDB

Mongo DB As Core Function For Python

http://docs.mongodb.org/ecosystem/drivers/python/

http://api.mongodb.org/python/current/tutorial.html

Search PyPi for 'mongo'

PyMongo

PyMongo is the recommended and officially supported way to work with MongoDB from Python.

PyMongo on PyPi https://pypi.python.org/pypi/pymongo/
Manual http://api.mongodb.org/python/current/index.html
Tutorial http://api.mongodb.org/python/current/tutorial.html
Examples http://api.mongodb.org/python/2.8rc0/examples/index.html
API http://api.mongodb.org/python/current/api/index.html

Python Drivers

Python Driver https://github.com/mongodb/mongo-python-driver
https://github.com/mongodb/mongo-python-driver/tree/master/pymongo

Basics

Basic Tutorial http://altons.github.io/python/2013/01/21/gentle-introduction-to-mongodb-using-pymongo/
Extended Tutorial http://www.bogotobogo.com/python/MongoDB_PyMongo/python_MongoDB_pyMongo_tutorial_installing.php

Search wiki for 'pymongo'

Mongo Engine

http://mongoengine.org/

https://pypi.python.org/pypi/mongoengine

MongoEngine is a Python Object-Document Mapper for working with MongoDB.

http://mongoengine-odm.readthedocs.org/

https://github.com/MongoEngine/mongoengine

Dependencies: pymongo>=2.7.1, sphinx (optional - for documentation generation)

Tutorial - http://docs.mongoengine.org/en/latest/tutorial.html

User Guide - http://docs.mongoengine.org/en/latest/guide/index.html

Signals - http://docs.mongoengine.org/en/latest/guide/signals.html

Signal support is provided by the excellent blinker library. If you wish to enable signal support this library must be installed, though it is not required for MongoEngine to function ...

Available signals include:

pre_init

Called during the creation of a new Document or EmbeddedDocument instance, after the constructor arguments have been collected but before any additional processing has been done to them.

post_init

Called after all processing of a new Document or EmbeddedDocument instance has been completed.

pre_save

Called within save() prior to performing any actions.

pre_save_post_validation

Called within save() after validation has taken place but before saving.

post_save

Called within save() after all actions (validation, insert/update, cascades, clearing dirty flags) have completed successfully. Passed the additional boolean keyword argument created to indicate if the save was an insert or an update.

pre_delete

Called within delete() prior to attempting the delete operation.

post_delete

Called within delete() upon successful deletion of the record.

pre_bulk_insert

Called after validation of the documents to insert, but prior to any data being written.

post_bulk_insert

Called after a successful bulk insert operation. As per pre_bulk_insert, the document argument is omitted and replaced with a documents argument.

... you can also define your handlers within your subclass:

import logging
from datetime import datetime

from mongoengine import *
from mongoengine import signals

class Author(Document):
    name = StringField()

    @classmethod
    def pre_save(cls, sender, document, **kwargs):
        logging.debug("Pre Save: %s" % document.name)

    @classmethod
    def post_save(cls, sender, document, **kwargs):
        logging.debug("Post Save: %s" % document.name)
        if 'created' in kwargs:
            if kwargs['created']:
                logging.debug("Created")
            else:
                logging.debug("Updated")

signals.pre_save.connect(Author.pre_save, sender=Author)
signals.post_save.connect(Author.post_save, sender=Author)

Server Side Javascript - http://docs.mongoengine.org/en/latest/guide/querying.html#server-side-javascript-execution

def sum_field(document, field_name, include_negatives=True):
    code = """
    function(sumField) {
        var total = 0.0;
        db[collection].find(query).forEach(function(doc) {
            var val = doc[sumField];
            if (val >= 0.0 || options.includeNegatives) {
                total += val;
            }
        });
        return total;
    }
    """
    options = {'includeNegatives': include_negatives}
    return document.objects.exec_js(code, field_name, **options)

API Reference - http://docs.mongoengine.org/en/latest/apireference.html

Search wiki for 'mongoengine'

Mongo Alchemy

https://pypi.python.org/pypi/MongoAlchemy/

Document-Object Mapper/Toolkit for Mongo Databases

http://www.mongoalchemy.org/

Turn MongoDB documents into Python objects and vice-versa, add schemas and validatation to your models, and allow the separation of the python and mongo representations of your data.

Support for all of the basic mongo types.
Separate Python and Mongo names. Field and collection names can be overridden.
Indexing on dict keys. MA provides a dict-like field which can have arbitrary key and value types as well as allowing indexing on the keys — not normally possible in Mongo. See: KVField
Computed values, generate from other fields. See: ComputedField
Created and Modified fields based on the computed fields which record the date something was first created or last updated.
Timezone support. A timezone can be passed using pytz and all dates will have timezone data attached and be converted to the given timezone.
User-defined validation — Provide your own validation functions for simple validations of fields. See Field
User-defined fields — For more customization, entirely new fields can be created
A field that can hold arbitrary values: AnythingField
Validation happens at assignment time, so you’ll know exactly where
Indexes are defined on the class

https://github.com/jeffjenkins/MongoAlchemy

This project is in maintenance mode. I'm accepting pull requests and fixing minor bugs, but you should not expect any significant new features or rearchitecting.

Ming

https://pypi.python.org/pypi/Ming

Database mapping layer for MongoDB on Python. Includes schema enforcement and some facilities for schema migration.

http://sourceforge.net/projects/merciless/files/

http://sourceforge.net/p/merciless/code/ci/master/tree/

http://sourceforge.net/p/merciless/code/ci/master/tree/docs/tour.rst

Specifying a Migration

One of the most irritating parts of maintaining an application for a while is the need to do data migrations from one version of the schema to another. While Ming can't completely remove the pain of migrations, it does seek to make migrations as simple as possible ...

All we need to do is include the previous schema, a migration function in our :class:__mongometa__ <ming.base.Document.__mongometa__> object, and a way to force the migration. For the 'forcing' part, we'll add a version field to the new schema:

http://blog.mongodb.org/post/27907941873/using-the-python-toolkit-ming-to-accelerate-your

Also See

http://www.ibm.com/developerworks/opensource/library/os-django-mongo/index.html

PythonTornado#MongoDBasCoreFunction

Last modified 2 years ago Last modified on 03/31/2015 01:48:03 PM

Attachments (1)

Download all attachments as: .zip