Search code examples
mongodbazureazure-cosmosdbazure-cosmosdb-mongoapi

How to create an insert trigger on Azure CosmosDB using MongoDB API


I would like to implement this solution from Mongodb Inc using a CosmosDB trigger, but I don't know if triggers using the MongoDB API are possible, and if they are, I can't seem to find any examples. Here's a simple working javascript that implements that solution on the client side:

function getNextSequenceValue(sequenceName){

   var sequenceDocument = db.counters.findAndModify({
      query:{_id: sequenceName },
      update: {$inc:{sequence_value:1}},
      new:true
   });

   return sequenceDocument.sequence_value;
}

db.products.insert({
   "_id":getNextSequenceValue("productid"),
   "product_name":"Apple iPhone",
   "category":"mobiles"
})

Would it be possible to do this server side using a CosmosDB trigger?


Solution

  • Better late than never and maybe someone will come across.

    Azure Cosmos DB supports only triggers, UDF and stored procedure for the CORE (SQL) API:
    https://learn.microsoft.com/en-us/azure/azure-functions/functions-create-cosmos-db-triggered-function

    Azure Cosmos DB bindings are only supported for use with the SQL API. For all other Azure Cosmos DB APIs, you should access the database from your function by using the static client for your API, including Azure Cosmos DB's API for MongoDB, Cassandra API, Gremlin API, and Table API.