Skip to content
Myr

simplify mongoengine doc, redirect from mongokit

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Lord · committed by David Lord · parent 4e280b4 · Browse files · 2 files+52 added−95 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+52 added−95 removed

  • other:+52 added−95 removed

2 files+52 added−95 removed

modified:docs/patterns/mongoengine.rst+45 added-95 removed
1.. mongoengine-pattern:1MongoDB with MongoEngine2========================33MongoEngine in Flask4====================4Using a document database like MongoDB is a common alternative to5relational SQL databases. This pattern shows how to use6`MongoEngine`_, a document mapper library, to integrate with MongoDB.76Using a document database rather than a full DBMS gets more common these days.7This pattern shows how to use MongoEngine, a document mapper library, to8integrate with MongoDB.8A running MongoDB server and `Flask-MongoEngine`_ are required. ::910This pattern requires a running MongoDB server, MongoEngine_ and Flask-MongoEngine_11libraries installed::1210 pip install flask-mongoengine1112.. _MongoEngine: http://mongoengine.org16.. _Flask-MongoEngine: http://docs.mongoengine.org/projects/flask-mongoengine/en/latest/>`_13.. _Flask-MongoEngine: https://flask-mongoengine.readthedocs.io141516Configuration17-------------1821Basic setup can be done by defining ``MONGODB_SETTINGS`` on App config and then22creating a ``MongoEngine`` instance::19Basic setup can be done by defining ``MONGODB_SETTINGS`` on20``app.config`` and creating a ``MongoEngine`` instance. ::2122 from flask import Flask23 from flask_mongoengine import MongoEngine2425 app = Flask(__name__)26 app.config['MONGODB_SETTINGS'] = {29 'host': "mongodb://localhost:27017/mydb"27 "db": "myapp",28 }29 db = MongoEngine(app)303132Mapping Documents33-----------------3437To declare models that will represent your Mongo documents, just create a class that38inherits from ``Document`` and declare each of the fields::35To declare a model that represents a Mongo document, create a class that36inherits from ``Document`` and declare each of the fields. ::3740 from mongoengine import *38 import mongoengine as me3940 class Movie(me.Document):41 title = me.StringField(required=True)42 year = me.IntField()43 rated = me.StringField()44 director = me.StringField()45 actors = me.ListField()4643 class Movie(Document):47If the document has nested fields, use ``EmbeddedDocument`` to48defined the fields of the embedded document and49``EmbeddedDocumentField`` to declare it on the parent document. ::5045 title = StringField(required=True)46 year = IntField()47 rated = StringField()48 director = StringField()49 actors = ListField()51 class Imdb(me.EmbeddedDocument):52 imdb_id = me.StringField()53 rating = me.DecimalField()54 votes = me.IntField()5551If the model has embedded documents, use ``EmbeddedDocument`` to defined the fields of52the embedded document and ``EmbeddedDocumentField`` to declare it on the parent document::5354 class Imdb(EmbeddedDocument):5556 imdb_id = StringField()57 rating = DecimalField()58 votes = IntField()596061 class Movie(Document):56 class Movie(me.Document):6257 ...64 imdb = EmbeddedDocumentField(Imdb)58 imdb = me.EmbeddedDocumentField(Imdb)596061Creating Data62-------------6370Just create the objects and call ``save()``::64Instantiate your document class with keyword arguments for the fields.65You can also assign values to the field attributes after instantiation.66Then call ``doc.save()``. ::6768 bttf = Movie(title="Back To The Future", year=1985)69 bttf.actors = [70 "Michael J. Fox",
5 unmodified lines
7677Queries78-------7984Use the class ``objects`` attribute to make queries::80Use the class ``objects`` attribute to make queries. A keyword argument81looks for an equal value on the field. ::8286 bttf = Movies.objects(title="Back To The Future").get() # Throw error if not unique83 bttf = Movies.objects(title="Back To The Future").get_or_404()8488``objects`` is an iterable. Query operators may be user by concatenating it with the document89key using a double-underscore::85Query operators may be used by concatenating them with the field name86using a double-underscore. ``objects``, and queries returned by87calling it, are iterable. ::8889 some_theron_movie = Movie.objects(actors__in=["Charlize Theron"]).first()9091 for recents in Movie.objects(year__gte=2017):92 print(recents.title)9396Available operators are as follows:9498* ``ne`` -- not equal to99* ``lt`` -- less than100* ``lte`` -- less than or equal to101* ``gt`` -- greater than102* ``gte`` -- greater than or equal to103* ``not`` -- negate a standard check, may be used before other operators (e.g.104 ``Q(age__not__mod=5)``)105* ``in`` -- value is in list (a list of values should be provided)106* ``nin`` -- value is not in list (a list of values should be provided)107* ``mod`` -- ``value % x == y``, where ``x`` and ``y`` are two provided values108* ``all`` -- every item in list of values provided is in array109* ``size`` -- the size of the array is110* ``exists`` -- value for field exists95Documentation96-------------97112String queries113::::::::::::::98There are many more ways to define and query documents with MongoEngine.99For more information, check out the `official documentation100<MongoEngine_>`_.101115The following operators are available as shortcuts to querying with regular116expressions:117118* ``exact`` -- string field exactly matches value119* ``iexact`` -- string field exactly matches value (case insensitive)120* ``contains`` -- string field contains value121* ``icontains`` -- string field contains value (case insensitive)122* ``startswith`` -- string field starts with value123* ``istartswith`` -- string field starts with value (case insensitive)124* ``endswith`` -- string field ends with value125* ``iendswith`` -- string field ends with value (case insensitive)126* ``match`` -- performs an $elemMatch so you can match an entire document within an array127128Some Tips129---------130131* Attributes can be set as ``unique``132* ``MongoEngine`` creates the ``_id`` attribute automatically to acess ``ObjectIds``133* You can add choices to string fields: ``StringField(choices=['Apple', 'Banana'])``134* If you don't want your class name to be the same name as the collection, you can define135 a ``meta`` class member and use the ``collection`` parameter::136137 class Movie(Document):138139 meta ={'collection': 'movie_documents'}140141Accessing PyMongo MongoClient142-----------------------------143144If, for some reason, you want to access PyMongo instance, use ``get_connection`` function::145146 from mongoengine.connection import get_connection147148 conn = get_connection()149 collection = conn.mydb.movie150 collection({'title': u'Days of Thunder'})151152For more information about MongoEngine, head over to the153`website <http://docs.mongoengine.org/>`_.102Flask-MongoEngine adds helpful utilities on top of MongoEngine. Check103out their `documentation <Flask-MongoEngine_>`_ as well.
added:docs/patterns/mongokit.rst+7 added
1:orphan:23MongoDB with MongoKit4=====================56MongoKit is no longer maintained. See :doc:`/patterns/mongoengine`7instead.