EventGet 50% off your ticket to MongoDB.local NYC on May 2. Use code Web50!Learn more >>
MongoDB Developer
Atlas
plus
Sign in to follow topics
MongoDB Developer Centerchevron-right
Developer Topicschevron-right
Productschevron-right
Atlaschevron-right

Triggers Treats and Tricks - Auto-Increment a Running ID Field

Pavel Duchovny3 min read • Published Dec 20, 2021 • Updated Sep 23, 2022
Atlas
Facebook Icontwitter iconlinkedin icon
Rate this article
star-empty
star-empty
star-empty
star-empty
star-empty
In this blog series, we are trying to inspire you with some reactive Realm trigger use cases. We hope these will help you bring your application pipelines to the next level.
Essentially, triggers are components in our Atlas projects/Realm apps that allow a user to define a custom function to be invoked on a specific event.
  • Database triggers: We have triggers that can be scheduled based on database events—like deletes, inserts, updates, and replaces—called database triggers.
  • Scheduled triggers: We can schedule a trigger based on a cron expression via scheduled triggers.
  • Authentication triggers: These triggers are only relevant for Realm authentication. They are triggered by one of the Realm auth providers' authentication events and can be configured only via a Realm application.
For this blog post, I would like to showcase an auto-increment of a running ID in a collection similar to relational database sequence use. A sequence in relational databases like Oracle or SqlServer lets you use it to maintain a running ID for your table rows.
If we translate this into a students collection example, we would like to get the studentId field auto incremented.
I wanted to share an interesting solution based on triggers, and throughout this article, we will use a students collection example with studentsId field to explain the discussed approach.

Prerequisites

First, verify that you have an Atlas project with owner privileges to create triggers.
If you haven't yet set up your free cluster on MongoDB Atlas, now is a great time to do so. You have all the instructions in this blog post.

The Idea Behind the Main Mechanism

The main flow of the auto-increment trigger concept
Three main components allow our auto-increment mechanism to function.

1. Define a Source Collection

We should pick the collection that we need the auto-increment to work upon (students) and we can define a unique index on that field. This is not a must but it makes sense:

2. Define a Generic Function to Auto-Increment the ID

In order for us to reuse the auto-increment code for more than one collection, I've decided to build a generic function and later associate it with the relevant triggers. Let's call the function autoIncrement. This function will receive an "insert" event from the source collection and increment a helper counters collection document that stores the current counter per collection. It uses findOneAndUpdate to return an automatically incremented value per the relevant source namespace, using the _id as the namespace identifier. Once retrieved, the source collection is being set with a generic field called <COLLECTION_NAME>Id (in this example, studentsId).
Important: Replace <ATLAS-SERVICE> with your linked service. The default value is "mongodb-atlas" if you have only one cluster linked to your Realm application.
Note that when we query and increment the counter, we expect to get the new version of the document returnNewDocument: true and upsert: true in case this is the first document.
The counter collection document after the first run on our student collection will look like this:

3. Building the Trigger on Insert Operation and Associating it with Our Generic Function

Now let's define our trigger based on our Atlas cluster service and our database and source collection, in my case, app.students.
Please make sure to select "Event Ordering" toggled to "ON" and the "insert" operation.
trigger settings page
Now let's associate it with our pre-built function: autoIncrement.
prebuilt function selection page
Once we will insert our document into the collection, it will be automatically updated with a running unique number for studentsId.
inserted documents have the unique student id field

Wrap Up

With the presented technique, we can leverage triggers to auto-increment and populate id fields. This may open your mind to other ideas to design your next flows on MongoDB Realm.
In the following article in this series, we will use triggers to auto-translate our documents and benefit from Atlas Search's multilingual abilities.
If you have questions, please head to our developer community website where the MongoDB engineers and the MongoDB community will help you build your next big idea with MongoDB.

Facebook Icontwitter iconlinkedin icon
Rate this article
star-empty
star-empty
star-empty
star-empty
star-empty
Related
Tutorial

Influence Search Result Ranking with Function Scores in Atlas Search


Feb 03, 2023 | 5 min read
Video

The Atlas Search 'cene: Season 1


Dec 15, 2023 | 2 min
Tutorial

Get Started with Atlas Stream Processing: Creating Your First Stream Processor


Feb 13, 2024 | 4 min read
Tutorial

Building a Scalable Media Management Back End: Integrating Node.js, Azure Blob Storage, and MongoDB


Dec 13, 2023 | 10 min read
Table of Contents