Skip to main content

Pip.Services Logo
MongoDB components for Python

This module is a part of the Pip.Services polyglot microservices toolkit.

The MongoDB module simplifies how we work with Mongo databases and contains everything you need to start working with MongoDB.

The module contains the following packages:

  • Build - contains a factory for creating MongoDB persistence components.
  • Connect - instruments for configuring connections to the database. The component receives a set of configuration parameters and uses them to generate all necessary database connection parameters.
  • Persistence - abstract classes for working with the database that can be used for connecting to collections and performing basic CRUD operations.

Quick links:

Use

Install the Python package as

pip install pip_services3_mongodb

As an example, lets create persistence for the following data object.

from pip_services3_commons.data import IIdentifiable

class MyObject implements IIdentifiable {
  id: str;
  key: str;
  value: int;
}

The persistence component shall implement the following interface with a basic set of CRUD operations.

from pip_services3_commons.data import DataPage, PagingParams, FilterParams


class IMyPersistence:

    def get_page_by_filter(self, correlation_id: str, filter: FilterParams, paging: PagingParams) -> DataPage:
        pass

    def get_one_by_id(self, correlation_id: str, id: str) -> MyObject:
        pass

    def get_one_by_key(self, correlation_id: str, key: str) -> MyObject:
        pass

    def create(self, correlation_id: str, item: MyObject)-> MyObject:
        pass

    def update(self, correlation_id: str, item: MyObject)-> MyObject:
        pass

    def delete_by_id(self, correlation_id: str, id: str) -> MyObject:
        pass

To implement mongodb persistence component you shall inherit IdentifiableMongoDbPersistence. Most CRUD operations will come from the base class. You only need to override get_page_by_filter method with a custom filter function. And implement a get_one_by_key custom persistence method that doesn't exist in the base class.

from pip_services3_commons.data import FilterParams
from pip_services3_mongodb.persistence import IdentifiableMongoDbPersistence


class MyMongoDbPersistence(IdentifiableMongoDbPersistence):
    def __init__(self):
        super(MyMongoDbPersistence, self).__init__('myobjects')

    def __composeFilter(self, filterr):
        filterr = filterr or FilterParams()
        id = filterr.get_as_nullable_string("id")
        if id:
            filterr.update({'_id': id})
        temp_ids = filterr.get_as_nullable_string("ids")
        if temp_ids:
            ids = temp_ids.split(",")
            filterr.update({'_id': {'$in': ids}})
        ids = temp_ids.split(",") if temp_ids is not None else None
        if ids:
            filterr.update({'_id': {'$in': ids}})
        key = filterr.get_as_nullable_string("key")

        if key:
            filterr.update({'key': key})

        if len(filterr) > 0:
            return {'$and': filterr}
        else:
            return None

    def get_page_by_filter(self, correlation_id, filter, paging, sort=None, select=None):
        return super().get_page_by_filter(correlation_id, filter, paging, '_id', select)

    def get_one_by_key(self, correlation_id, key):

        filterr = {'key': key}
        item = self._collection.find_one(filterr)
        if item:
            self._logger.trace(correlation_id, "Retrieved from {} with key = {}", self._collection_name, key)
            item = self._convert_to_public(item)
            return item
        else:
            self._logger.trace(correlation_id, "Nothing found from {} with key = {}", self._collection_name, key)

Configuration for your microservice that includes mongodb persistence may look the following way.

...
{{#if MONGODB_ENABLED}}
- descriptor: pip-services:connection:mongodb:con1:1.0
  collection: {{MONGO_COLLECTION}}{{#unless MONGO_COLLECTION}}myobjects{{/unless}}
  connection:
    uri: {{{MONGO_SERVICE_URI}}}
    host: {{{MONGO_SERVICE_HOST}}}{{#unless MONGO_SERVICE_HOST}}localhost{{/unless}}
    port: {{MONGO_SERVICE_PORT}}{{#unless MONGO_SERVICE_PORT}}27017{{/unless}}
    database: {{MONGO_DB}}{{#unless MONGO_DB}}app{{/unless}}
  credential:
    username: {{MONGO_USER}}
    password: {{MONGO_PASS}}
    
- descriptor: myservice:persistence:mongodb:default:1.0
  dependencies:
    connection: pip-services:connection:mongodb:con1:1.0
{{/if}}
...

Develop

For development you shall install the following prerequisites:

  • Python 3.7+
  • Visual Studio Code or another IDE of your choice
  • Docker

Install dependencies:

pip install -r requirements.txt

Run automated tests:

python test.py

Generate API documentation:

./docgen.ps1

Before committing changes run dockerized build and test as:

./build.ps1
./test.ps1
./clear.ps1

Contacts

The Python version of Pip.Services is created and maintained by Sergey Seroukhov

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pip_services3_mongodb-3.0.5.tar.gz (16.2 kB view details)

Uploaded Source

File details

Details for the file pip_services3_mongodb-3.0.5.tar.gz.

File metadata

  • Download URL: pip_services3_mongodb-3.0.5.tar.gz
  • Upload date:
  • Size: 16.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.6.1 requests/2.22.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.50.2 CPython/3.8.2

File hashes

Hashes for pip_services3_mongodb-3.0.5.tar.gz
Algorithm Hash digest
SHA256 b268137beb7abdf123e7a3b077fc5372a165e0b9fa1efb07aff2008d29079ad9
MD5 82376ba63ea322811b5fd838e3301ad6
BLAKE2b-256 dc0921b4c02db957f8e1d73a18fd95e9003bac92ac8f4c088b824bbfe68aaf44

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page