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.
Earlier in our previous article "Improve efficiency of your SELECT queries" we discussed ways to profile and optimize the performance of SELECT queries. However, to write complex yet efficient SQL queries, there is a thing to remember about.
In one of our recent projects, we had an interesting case: the whole application was built around an interactive map for a fairly large shopping mall, and the main goal of the system was to plot the closest route to a user-selected destination.
Usually users' profiles are stored in single model. When there are multiple user types, separation is made by some field like user_type.Situation is a little more complicated when different data is needed for each user type.In this article I'll describe how I solve this task.
Programmatic generation of PDF files is a frequent task when developing applications that can export reports, bills, or questionnaires. In this article, we will consider three common tools for creating PDFs, including their installation and converting principles.