# Demystifying Stored Procedures in MongoDB

If you have ever used a SQL database, you might have heard about stored procedures. Stored procedures represent pre-written SQL code designed for reuse. By storing frequently used SQL queries as procedures, you can execute them repeatedly. Additionally, these procedures can be parameterized, allowing them to operate on specified parameter values. Oftentimes, developers find themselves wondering:

- Does MongoDB support stored procedures? 
- Where do you write the logic for stored procedures in MongoDB? 
- How can I run a query every midnight, like a CRON job?

In today’s article, we are going to answer these questions and demystify stored procedures in MongoDB.

## Does MongoDB support stored procedures?

Essentially, a stored procedure consists of a set of SQL statements capable of accepting parameters, executing tasks, and optionally returning values. In the world of MongoDB, we can achieve this using an aggregation pipeline. 

An aggregation pipeline, in a nutshell, is basically a series of stages where the output from a particular stage is an input for the next stage, and the last stage’s output is the final result. 

Now, every stage performs some sort of processing to the input provided to it, like filtering, grouping, shaping, calculating, etc. You can even perform vector search and full-text search using MongoDB’s unified developer data platform, Atlas.

Let's see how MongoDB’s aggregation pipeline, Atlas triggers, and change streams together can act as a super efficient, powerful, and flexible alternative to stored procedures.

## What is MongoDB Atlas?

MongoDB Atlas is a multi-cloud developer data platform focused on making it stunningly easy to work with data. It offers the optimal environment for running MongoDB, the leading non-relational database solution.

MongoDB's document model facilitates rapid innovation by directly aligning with the objects in your code. This seamless integration makes data manipulation more intuitive and efficient. With MongoDB, you have the flexibility to store data of diverse structures and adapt your schema effortlessly as your application evolves with new functionalities.

The Atlas database is available in 100+ regions across AWS, Google Cloud, and Azure. You can even take advantage of multi-cloud and multi-region deployments, allowing you to target the providers and regions that best serve your users. It has best-in-class automation and proven practices that guarantee availability, scalability, and compliance with the most demanding data security and privacy standards.

## What is an Atlas Trigger?

Database triggers enable the execution of server-side logic whenever a document undergoes addition, modification, or deletion within a connected Atlas cluster. 

Unlike conventional SQL data triggers confined to the database server, Atlas Triggers operate on a serverless compute layer capable of scaling autonomously from the database server. 

It seamlessly invokes Atlas Functions and can also facilitate event forwarding to external handlers via Amazon EventBridge.

## How can Atlas Triggers be invoked?

An Atlas Trigger might fire on:

- A specific operation type in a given collection, like insert, update, and delete. 
- An authentication event, such as User Creation or Deletion.
- A scheduled time, like a CRON job.

## Types of Atlas Triggers

There are three types of triggers in Atlas:

- Database triggers are used in scenarios where you want to respond when a document is inserted, changed, or deleted. 
- Authentication triggers can be used where you want to respond when a database user is created, logged in, or deleted.
- Scheduled triggers acts like a CRON job and run on a predefined schedule.

Refer to Configure Atlas Triggers for advanced options.

## Atlas Triggers in action

Let's compare how stored procedures can be implemented in SQL and MongoDB using triggers, functions, and aggregation pipelines.

### The SQL way

Here's an example of a stored procedure in MySQL that calculates the total revenue for the day every time a new order is inserted into an orders table:

```
DELIMITER $$

CREATE PROCEDURE UpdateTotalRevenueForToday()
BEGIN
    DECLARE today DATE;
    DECLARE total_revenue DECIMAL(10, 2);

    -- Get today's date
    SET today = CURDATE();

    -- Calculate total revenue for today
    SELECT SUM(total_price) INTO total_revenue
    FROM orders
    WHERE DATE(order_date) = today;

    -- Update total revenue for today in a separate table or perform any other necessary action
    -- Here, I'm assuming you have a separate table named 'daily_revenue' to store daily revenue
    -- If not, you can perform any other desired action with the calculated total revenue

    -- Update or insert the total revenue for today into the 'daily_revenue' table
    INSERT INTO daily_revenue (date, revenue)
    VALUES (today, total_revenue)
    ON DUPLICATE KEY UPDATE revenue = total_revenue;
END$$

DELIMITER ;
```

In this stored procedure:

- We declare two variables: today to store today's date and total_revenue to store the calculated total revenue for today.
- We use a SELECT statement to calculate the total revenue for today from the orders table where the order_date matches today's date.
- We then update the daily_revenue table with today's date and the calculated total revenue. If there's already an entry for today's date, it updates the revenue. Otherwise, it inserts a new row for today's date.

Now, we have to create a trigger to call this stored procedure every time a new order is inserted into the orders table. Here's an example of how to create such a trigger:

```
CREATE TRIGGER AfterInsertOrder
AFTER INSERT ON orders
FOR EACH ROW
BEGIN
    CALL UpdateTotalRevenueForToday();
END;
```

This trigger will call the UpdateTotalRevenueForToday() stored procedure every time a new row is inserted into the orders table.

### The MongoDB way

If you don’t have an existing MongoDB Database deployed on Atlas, start for free and get 500MBs of storage free forever.

Now, all we have to do is create an Atlas Trigger and implement an Atlas Function in it.

Let’s start by creating an Atlas database trigger. 

.

, are powerful alternatives to traditional stored procedures. MongoDB Atlas, the developer data platform, further enhances development flexibility with features like Atlas Functions and Triggers, enabling seamless integration of server-side logic within the database environment.

The migration from stored procedures to MongoDB is not just a technological shift; it represents a paradigm shift towards embracing a future-ready digital landscape. As organizations transition, they gain the ability to leverage MongoDB's innovative solutions, maintaining agility, enhancing performance, and adhering to contemporary development practices.

So, what are you waiting for? Sign up for Atlas today and experience the modern alternative to stored procedures in MongoDB.

  [1]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/bltcb5b2b2db6b3a2b6/65dce8447394e52da349971b/image1.png
  [2]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt5cbb9842024e79f1/65dce844ae62f722b74bdfe0/image2.png
  [3]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt529e154503e12f56/65dce844aaeb364e19a817e3/image3.png
  [4]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blta2a7b461deb6879d/65dce844aaeb36b5d5a817df/image4.png
  [5]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt5801d9543ac94f25/65dce8446c65d723e087ae99/image5.png
  [6]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt5ceb23e853d05d09/65dce845330e0069f27f5980/image6.png
  [7]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt626536829480d1be/65dce845375999f7bc70a71b/image7.png
  [8]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt1b1366584ee0766a/65dce8463b4c4f91f07ace17/image8.png