MongoDB is an open-source document-oriented database management system (DBMS) with flexible schemas. MongoDB was founded by Dwight Merriman and Eliot Horowitz who faced with development issues and struggled with relational database management system while building web applications.
According to one of its founders, the MongoDB name comes from the word humongous and simply means that the database can handle lots of data. Merriman and Horowitz helped to create the 10gen Inc. in 2007 with an aim to commercialise database program and related software. The company was renamed to MongoDB Inc. in 2013.
An open-source database was released in 2009. Now it is available under the Server Side Public License (SSPL) license terms.
The document itself is a set of key/value pairs. Documents have a dynamic schema. Dynamic schemas mean that documents from one collection do not necessarily have the same set of fields and structures. It also means that the common fields in the documents collections can contain different types of data. Below is an example of a document structure:
_id is the 12-byte hexadecimal number which assures the uniqueness of each document. You obviously can insert it in the document. If it’s not specified, MongoDB provides a unique ID for each document.
DBMS uses JSON style documents that are stored in the BSON binary format. Thanks to the GridFS protocol, MongoDB has the capability to store and retrieve files. Like the other document-oriented DBMS (CouchDB, etc.), MongoDB is not a relational DBMS. There is no such thing as a "transaction." Atomicity is only guaranteed on a whole document-level, so the partial update of the document can not happen. Also, there is no an "isolation" concept: any data that is read by one client can simultaneously be changed by another client.
The following are some of the MongoDB advantages:
|Rich data model||Yes||No||No|
|Localization of data||Yes||No||Yes|
So, how to use MongoDB in Python? Take a look at our short Python MongoDB tutorial.
PyMongo is a tool for working with MongoDB and is the official recommended way to work when using Mongo database in Python.
In PyMongo we use dictionaries to represent documents. As an example, the following dictionary might be used to represent a blog post:
Documents can contain native Python types (such as datetime.datetime) which will be automatically converted to and from the appropriate BSON types.
To add a document into the collection, we can use the insert_one() method:
The most useful type of query is the find_one method. This method returns a single document matching a query (or none, in case if there are no matches). Here we use find_one() to get the first document from the posts collection:
The result is a document that we inserted previously. find_one() also supports querying on specific elements that the document must match.
To get more documents, we use the find() method. find() returns a Cursor instance, which allows us to iterate over all matching documents.
Also, we can limit the find() returned results. We only get documents with author “Mike” here:
At the PyMongo core is the MongoClient object, which is used to make connections and queries to a MongoDB database cluster. It can be used to connect to a standalone mongod instance, a replica set or mongos instances. Repository: https://github.com/mongodb/mongo-python-driver
MongoEngine is ODM (Python MongoDB ORM, but for document-oriented database) that allows to work with MongoDB on Python. It uses simple declarative API similar to Django ORM.
To specify the Python MongoDB schema document, we create a class that is inherited from the Document base class. Fields are determined from adding the document’s class attributes.
Now, when we have identified how our documents will be structured, we begin adding some of the documents to the database. Firstly, we need to create an object:
We could also define our object using the attribute syntax:
Each document class (i.e. any class that is directly or indirectly inherited from the document) has an attribute and objects that are used to access the documents in the collection of database associated with this class. So, let's see how to get the headlines of our pages:
Here is a brief list of some of the main features of MongoEngine:
Motor is an async driver for MongoDB. It can be used as Tornado or asyncio-applications. Motor never blocks the event loop when connecting to MongoDB or when performing input/output operations. This driver is practically a wrapper over the entire API PyMongo for non-blocking access to MongoDB.
The tornado.gen module allows using subprogrammes to simplify an asynchronous code. It supports Tornado-applications with multiple IOLoops. It can transfer data from GridFS to Tornado RequestHandler, using stream_to_handler () or the GridFSHandler class.
Motor provides a single class-client - MotorClient. Unlike MongoClient PyMongo, MotorClient does not actually connect in the background on startup. Instead, it is connected on demand, at the first operation request.
Motor supports almost every PyMongo method, but the methods take an additional callback function.
Motor uses gevent-like method to wrap PyMongo and run its asynchronously, presenting a classic callback interface to Tronado applications. This driver can easily keep up with the PyMongo development in the future.
MotorEngine is created based on Motor. Motorengine is a port of MongoEngine.
MongoKit is a Python-module, a PyMongo wrapper, that brings structured schemes and screening layer.
MongoKit uses simple types of the Python data to describe the structure of the document. MongoKit is pretty fast and has access to clean PyMongo-layer without API changes to increase the speed. It has lots of additional features, such as automatic reference to a document, user types or i18n support. Documents are improved by the validate() Python-dictionaries method.
Document declaration is as follows:
Setting the link and registering our objects:
Saving an object will call the validate() method. A more complex structure can be used as follows:
Hope you managed to clear up for yourself how to use MongoDB with Python. When you select a Python driver for MongoDB, you should answer two questions:
In the case of asynchronous applications - you need Motor or MotorEngine.
All synchronous drivers are wrappers for PyMongo. If you do not need to fix the structure of the document, the easiest way for you is to work directly with PyMongo.
If you want to fix the structure of the documents in the code, you can take MongoEngine or MongoKit. Mainly, we are working with Django, so it is more natural for us to us MongoEngine.
Also you can contact us if you want to learn more about Python MongoDB best practices.
Read more about MVP development services and web app development.
It appears that not everyone knows that in python you can create classes dynamically without metaclasses. I'll show an example of how to do it.So we've learned how to use custom QuerySet to chain requests:Article.objects.old().public()Now we need to make it work for related objects:user.articles.old().public()This is done using use_for_related_fields, but it needs a little trick.
There was a task to submit form with ajax, with server side validation of course. Obvious solution is to do validation and return json with erros. I didn't like idea of writing separate view for validation and then inserting errors in form html on client side. Especially since I already had a generic template for django form with errors display. In this article I'll describe how I solved the task.
For local project settings, I use old trick with settings_local file:try:from settings_local import \*except ImportError:passSo in settings_local.py we can override variables from settings.py. I didn't know how to supplement them. For example how to add line to INSTALLED_APPS without copying whole list.Yesterday I finally understood that I can import settings from settings_local:# settings_local.pyfrom settings import \*INSTALLED_APPS += (# ...)