MongoDB usage examples

Connections to MongoDB databases are configured through outgoing MongoDB connection definitions.

Each definition creates a pool of connection objects that can be accessed by Zato services as in the examples below.

The underlying implementation uses pymongo.MongoClient objects and it is MongoClient that maintains the connection pool - it is not required to explicitly open nor to close the MongoDB connections in one’s services, the pool is maintained automatically.

Sending documents to MongoDB

Create a new outgoing MongoDB connection and send a document like in this example.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# -*- coding: utf-8 -*-

# Zato
from zato.server.service import Service

# For type hints
if 0:
    from pymongo import MongoClient
    from pymongo.collection import Collection

    Collection = Collection
    MongoClient = MongoClient

class SendMongoDB(Service):

    def handle(self):

        # Get a handle to a MongoDB client object
        conn = self.out.mongodb.get('My Mongo').conn.client # type: MongoClient

        # Select a database and collection
        db = conn.admin
        collection = db.my_collection # type: Collection

        result = collection.insert_one({
            'My object': 'My data'
        })

        # Print out the newly inserted document's ID
        self.logger.info('Inserted as %s', result.inserted_id)

In logs:

1
INFO - Inserted as 5ef8ca91562c38025289ad84

Receiving documents from MongoDB

Create a new outgoing MongoDB connection and read documents like in this example.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# -*- coding: utf-8 -*-

# Zato
from zato.server.service import Service

# For type hints
if 0:
    from pymongo import MongoClient
    from pymongo.collection import Collection

    Collection = Collection
    MongoClient = MongoClient

class ReadMongoDB(Service):

    def handle(self):

        # Get a handle to a MongoDB client object
        conn = self.out.mongodb.get('My Mongo').conn.client # type: MongoClient

        # Select a database and collection
        db = conn.admin
        collection = db.my_collection # type: Collection

        # Read a document from the database
        result = collection.find_one()

        # Print out the document read in
        self.logger.info('Document is %s', result)

In logs:

1
INFO - Document is {'_id': '5ef8ca91562c38025289ad84', 'My object': 'My data'}