Search code examples
python-3.xmongodb-querydatabase-triggerpymongo-3.xmongodb-stitch

How to write trigger and functions code in python(pymongo) for MongoDB Stitch instead of NodeJS(mongoose)


I want to setup a connection of MongoDB Stitch with my Python Script and fire trigger on database events to execute a python function.

I've seen this article which shows connection with stitch of python script. I cannot find how to do this type of import of JavaScript in python.

I expect if there is deletion of a known collection's TTL index document in my database, then MongoDB will fire up trigger to my Python Script and execute a function in my Python Script. How can I achieve this?


Solution

  • MongoDB Stitch Triggers listen for application events of a configured type and are each linked with a specific Stitch function. This function is Stitch hosted function, and currently MongoDB Stitch functions can only be written with JavaScript (ES6+). So, currently there is no way to write Python function for Stitch triggers. Depending on what you're trying to do, if it's simple enough I would suggest to convert the Python logic to JavaScript.

    There are also a couple of workarounds that you could try depending on your requirements and use case:

    1. Open MongoDB ChangeStreams using pymongo.change_stream to watch changes on a collection, a database, or the entire cluster. Stitch triggers is also utilising MongoDB ChangeStream as the underlying mechanism. The difference here is that the execution is not in Stitch servers, but on your application server. For example:

      pipeline = [{'$match': {'operationType': 'insert'}}]
      with db.collection.watch(pipeline) as stream:
          for insert_change in stream:
              # Trigger something based on an insert of a document 
              print(insert_change)
      
    2. Write a simple Stitch function (in JavaScript) for triggers that calls your own application web server. For example, write a Python Flask web server that accepts REST API endpoints i.e. https://your.custom.server.com/api/v1/insert?event=101 then execute your Python function. Here you delegate the changestream watch to Stitch, but have a server that waits for incoming calls from Stitch.