MongoDB connections

One of the newest additions in Zato 3.1 are MongoDB connections - learn in this article how to create and use them in your Python API services.

Dashboard

As with most parts of Zato, the most straightforward way to create a new connection definition is to fill out a form in web-admin.

Note that MongoDB connections pack in a lot of options and, to keep the user interface as lightweight as possible, only the most commonly used ones are displayed in the default view and the rest needs to be toggled as needed.

Pinging

To confirm that the connection is configured correctly, including credentials to connect with, you can ping it.

If everything is set up correctly, a response such as the one below will be returned.

Python API

A sample Python service may look like below - the client returned by self.out.mongodb is an instance of pymongo.MongoClient so anything that the PyMongo library can do is achievable from Zato too.

# -*- coding: utf-8 -*-

from __future__ import absolute_import, division, print_function, unicode_literals

# Zato
from zato.server.service import Service

class MyService(Service):
    def handle(self):

        # Obtain a MongoDB client
        client = self.out.mongodb['My MongoDB Connection'].conn.client

        # Select a database
        db = client.test

        # Insert a document
        db.my_collection.insert_one({'My object': 'My data'})

        # Get all documents already stored
        result = db.my_collection.find()

        # Print them out to logs
        for item in result:
            self.logger.info('Item: %s', item)

Now, in log files:

INFO - Item: {'_id': ObjectId('5c99f8aa5ecb8221dcb3ff73'), 'My object': 'My data'}
INFO - Item: {'_id': ObjectId('5c99ffdf5ecb8221dcb3ff74'), 'My object': 'My data'}
INFO - Item: {'_id': ObjectId('5c99ffe05ecb8221dcb3ff75'), 'My object': 'My data'}

Summary

This is everything that is required - once a connection is created it can be used immediately in Zato services.

Because each connection is actually an instance of the official MongoDB Python client, there are no limits to what can be done with them - building MongoDB-based applications with Zato is now a fully supported possibility.