MongoDB with MongoEngine¶
Using a document database like MongoDB is a common alternative torelational SQL databases. This pattern shows how to useMongoEngine, a document mapper library, to integrate with MongoDB.
A running MongoDB server andFlask-MongoEngine are required.
pipinstallflask-mongoengine
Configuration¶
Basic setup can be done by definingMONGODB_SETTINGS
onapp.config
and creating aMongoEngine
instance.
fromflaskimportFlaskfromflask_mongoengineimportMongoEngineapp=Flask(__name__)app.config['MONGODB_SETTINGS']={"db":"myapp",}db=MongoEngine(app)
Mapping Documents¶
To declare a model that represents a Mongo document, create a class thatinherits fromDocument
and declare each of the fields.
importmongoengineasmeclassMovie(me.Document):title=me.StringField(required=True)year=me.IntField()rated=me.StringField()director=me.StringField()actors=me.ListField()
If the document has nested fields, useEmbeddedDocument
todefined the fields of the embedded document andEmbeddedDocumentField
to declare it on the parent document.
classImdb(me.EmbeddedDocument):imdb_id=me.StringField()rating=me.DecimalField()votes=me.IntField()classMovie(me.Document):...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 calldoc.save()
.
bttf=Movie(title="Back To The Future",year=1985)bttf.actors=["Michael J. Fox","Christopher Lloyd"]bttf.imdb=Imdb(imdb_id="tt0088763",rating=8.5)bttf.save()
Queries¶
Use the classobjects
attribute to make queries. A keyword argumentlooks for an equal value on the field.
bttf=Movies.objects(title="Back To The Future").get_or_404()
Query operators may be used by concatenating them with the field nameusing a double-underscore.objects
, and queries returned bycalling it, are iterable.
some_theron_movie=Movie.objects(actors__in=["Charlize Theron"]).first()forrecentsinMovie.objects(year__gte=2017):print(recents.title)
Documentation¶
There are many more ways to define and query documents with MongoEngine.For more information, check out theofficial documentation.
Flask-MongoEngine adds helpful utilities on top of MongoEngine. Checkout theirdocumentation as well.