MongoDB with MongoEngine
Using a document database like MongoDB is a common alternative to relational SQL databases. This pattern shows how to use MongoEngine, a document mapper library, to integrate with MongoDB.
A running MongoDB server and Flask-MongoEngine are required.
1. pip install flask-mongoengine
Configuration
Basic setup can be done by defining MONGODB_SETTINGS on app.config and creating a MongoEngine instance.
1. from flask import Flask
2. from flask_mongoengine import MongoEngine
4. app = Flask(__name__)
5. app.config['MONGODB_SETTINGS'] = {
6. "db": "myapp",
7. }
8. db = MongoEngine(app)
Mapping Documents
To declare a model that represents a Mongo document, create a class that inherits from Document and declare each of the fields.
1. import mongoengine as me
3. class Movie(me.Document):
4. title = me.StringField(required=True)
5. year = me.IntField()
6. rated = me.StringField()
7. director = me.StringField()
8. actors = me.ListField()
If the document has nested fields, use EmbeddedDocument to defined the fields of the embedded document and EmbeddedDocumentField to declare it on the parent document.
1. class Imdb(me.EmbeddedDocument):
2. imdb_id = me.StringField()
3. rating = me.DecimalField()
4. votes = me.IntField()
6. class Movie(me.Document):
7. ...
8. imdb = me.EmbeddedDocumentField(Imdb)
Creating Data
Instantiate your document class with keyword arguments for the fields. You can also assign values to the field attributes after instantiation. Then call doc.save().
1. bttf = Movie(title="Back To The Future", year=1985)
2. bttf.actors = [
3. "Michael J. Fox",
4. "Christopher Lloyd"
5. ]
6. bttf.imdb = Imdb(imdb_id="tt0088763", rating=8.5)
7. bttf.save()
Queries
Use the class objects attribute to make queries. A keyword argument looks for an equal value on the field.
1. bttf = Movies.objects(title="Back To The Future").get_or_404()
Query operators may be used by concatenating them with the field name using a double-underscore. objects, and queries returned by calling it, are iterable.
1. some_theron_movie = Movie.objects(actors__in=["Charlize Theron"]).first()
3. for recents in Movie.objects(year__gte=2017):
4. print(recents.title)
Documentation
There are many more ways to define and query documents with MongoEngine. For more information, check out the official documentation.
Flask-MongoEngine adds helpful utilities on top of MongoEngine. Check out their documentation as well.
