Welcome to Flask MongoAlchemy’s documentation!

Flask-MongoAlchemy adds support for MongoDB on Flask using MongoAlchemy. Source code and issue tracking are available at Github. If you want to get started, check out the example source code.


You can easily install using pip:

$ [sudo] pip install Flask-MongoAlchemy

If you prefer, you may use the latest source version by cloning the following git repository:

$ git clone https://github.com/cobrateam/flask-mongoalchemy.git
$ cd flask-mongoalchemy
$ [sudo] python setup.py develop

Make sure you have MongoDB installed to use it.


It is very easy and fun to use Flask-MongoAlchemy to proxy between Python and MongoDB.

All you have to do is create a MongoAlchemy object and use it to declare documents. Here is a complete example:

from flask import Flask
from flask.ext.mongoalchemy import MongoAlchemy
app = Flask(__name__)
app.config['MONGOALCHEMY_DATABASE'] = 'library'
db = MongoAlchemy(app)

class Author(db.Document):
    name = db.StringField()

class Book(db.Document):
    title = db.StringField()
    author = db.DocumentField(Author)
    year = db.IntField()

As you can see, extending the Document is all you need to create a document.

Now you can create authors and books:

>>> from application import Author, Book
>>> mark_pilgrim = Author(name='Mark Pilgrim')
>>> dive = Book(title='Dive Into Python', author=mark_pilgrim, year=2004)

And save them:

>>> mark_pilgrim.save()
>>> dive.save()

If you make any changes on a document, you may call save() again:

>>> mark_pilgrim.name = 'Mark Stalone'
>>> mark_pilgrim.save()

And you can remove a document from the database by calling its remove() method:

>>> dive.remove()

Another basic operation is querying for documents. Every document has a query class property. It’s very simple to use it:

>>> mark = Author.query.get('76726')
>>> mark.name = 'Mark Pilgrim'
>>> mark.save()

You also can use the filter method instead of the get() method:

>>> mark = Author.query.filter(Author.name == 'Mark Pilgrim').first()
>>> mark.name = 'Steve Jobs'
>>> mark.save()

Do you want to go further? Dive deep into the API docs.

Using authenticated connections

It’s possible to use authentication to connect to a MongoDB server. The authentication can be server based or database based.

The default behavior is to use server based authentication, to use database based authentication, you need to turn off the config value MONGOALCHEMY_SERVER_AUTH (see the next section for more detail on configuration values):

>>> app.config['MONGOALCHEMY_SERVER_AUTH'] = False

Configuration values

The following configuration values are present in Flask-MongoAlchemy:

MONGOALCHEMY_DATABASE The database name that should be used for the connection.

The MongoDB server.

Default value: localhost


Listening port of the MongoDB server.

Default value: 27017


User for database connection.

Default value: None


Password for database connection.

Default value: None


Use session in safe mode. When in safe mode, all methods like save and delete wait for the operation to complete.

Default value: False


Pass extra options to the MongoDB server when connecting.

e.g.: safe=true Default value: None


Boolean value indicating to use server based authentication or not. When False, will use database based authentication.

Default value: True


Name of the replica set to be used. Empty for no replica sets.

Default value: ````

MONGOALCHEMY_CONNECTION_STRING The connection string to use, when it’s defined, Flask MongoAlchemy will ignore other connection settings previously specified.

When MongoAlchemy or init_app() are invoked with only one argument (the Flask instance), a configuration value prefix of MONGOALCHEMY is assumed; this can be overridden with the config_prefix argument, for example:

app = Flask(__name__)

# defaulting to MONGOENGINE prefix
mongo1 = MongoAlchemy(app)

# using another database config
app.config['OTHER_DBNAME'] = 'other'
mongo2 = MongoAlchemy(app, config_prefix='OTHER')


This part of the documentation documents all the public classes and functions in Flask-MongoAlchemy.


class flask.ext.mongoalchemy.MongoAlchemy(app=None, config_prefix='MONGOALCHEMY')

Class used to control the MongoAlchemy integration to a Flask application.

You can use this by providing the Flask app on instantiation or by calling an init_app() method an instance object of MongoAlchemy. Here an example of providing the application on instantiation:

app = Flask(__name__)
db = MongoAlchemy(app)

And here calling the init_app() method:

db = MongoAlchemy()

def init_app():
    app = Flask(__name__)
    return app
init_app(app, config_prefix='MONGOALCHEMY')

This callback can be used to initialize an application for the use with this MongoDB setup. Never use a database in the context of an application not initialized that way or connections will leak.


class flask.ext.mongoalchemy.Document(retrieved_fields=None, loading_from_db=False, **kwargs)

Base class for custom user documents.

query = None

an instance of query_class. Used to query the database for instances of this document.


the query class used. The query attribute is an instance of this class. By default BaseQuery is used.

alias of BaseQuery


Removes the document itself from database.

The optional safe argument is a boolean that specifies if the remove method should wait for the operation to complete.


Saves the document itself in the database.

The optional safe argument is a boolean that specifies if the remove method should wait for the operation to complete.


class flask.ext.mongoalchemy.BaseQuery(type, session)

Base class for custom user query classes.

This class provides some methods and can be extended to provide a customized query class to a user document.

Here an example:

from flask.ext.mongoalchemy import BaseQuery
from application import db

class MyCustomizedQuery(BaseQuery):

    def get_johns(self):
        return self.filter(self.type.first_name == 'John')

class Person(db.Document):
    query_class = MyCustomizedQuery
    name = db.StringField()

And you will be able to query the Person model this way:

>>> johns = Person.query.get_johns().first()

Note: If you are extending BaseQuery and writing an __init__ method, you should always call this class __init__ via super keyword.

Here an example:

class MyQuery(BaseQuery):

    def __init__(self, *args, **kwargs):
        super(MyQuery, self).__init__(*args, **kwargs)

This class is instantiated automatically by Flask-MongoAlchemy, don’t provide anything new to your __init__ method.


Returns the first result of this query, or aborts with 404 if the result doesn’t contain any row


Returns a Document instance from its mongo_id or None if not found


Like get() method but aborts with 404 if not found instead of returning None

paginate(page, per_page=20, error_out=True)

Returns per_page items from page page By default, it will abort with 404 if no items were found and the page was larger than 1. This behaviour can be disabled by setting error_out to False.

Returns a Pagination object.


class flask.ext.mongoalchemy.Pagination(query, page, per_page, total, items)

Internal helper class returned by paginate().


Returns True if a next page exists.


Returns True if a previous page exists.

items = None

list of items for the current page


Return a Pagination object for the next page.


The next page number.

page = None

current page number


The total number of pages

per_page = None

number of items to be displayed per page


Return a Pagination object for the previous page.


The previous page number.

query = None

query object used to create this pagination object.

total = None

total number of items matching the query

Indices and tables

Fork me on GitHub