Build an Inventory Management System Using MongoDB Atlas
This tutorial was written by Rami Pinto. In the competitive retail landscape, having the right stock in the right place at the right time is crucial. Too little inventory when and where it’s needed can create unhappy customers. However, a large inventory can increase costs and risks associated with its storage. Companies of all sizes struggle with inventory management. Solutions such as a single view of inventory, real-time analytics, and event-driven architectures can help your businesses overcome these challenges and take your inventory management to the next level. By the end of this guide, you'll have inventory management up and running, capable of all the solutions mentioned above. We will walk you through the process of configuring and using MongoDB Atlas as your back end for your Next.js app, a powerful framework for building modern web applications with React. The architecture we're about to set up is depicted in the diagram below: This will result in a multi-store inventory management solution capable of efficiently navigating through your product catalog, receiving alerts, and automating restock workflows, all while maintaining control of your inventory through real-time analytics. Check out the end result here. Let's get started! Prerequisites Before you begin working with this project, ensure that you have the following prerequisites set up in your development environment: Git (version 2.39 or higher): This project utilizes Git for version control. Make sure you have Git installed on your system. You can download and install the latest version of Git from the official website: Git Downloads. Node.js (version 20 or higher) and npm (version 9.6 or higher): The project relies on the Node.js runtime environment and npm (Node Package Manager) to manage dependencies and run scripts. You need to have them both installed on your machine. You can download Node.js from the official website: Node.js Downloads. After installing Node.js, npm will be available by default. mongorestore (version 100.9.4 or higher): The mongorestore tool loads data from a binary database dump. The dump directory in the GitHub repository includes a demo database with preloaded collections, views, and indexes, to get you up and running in no time. This tool is part of the MongoDB Database Tools package. Follow the Database Tools Installation Guide to install mongorestore. When you are done with the installation, run mongorestore --version in your terminal to verify the tool is ready to use. MongoDB Atlas cluster (M0 or higher): This project uses a MongoDB Atlas cluster to manage the database. You should have a MongoDB Atlas account and a minimum free tier cluster set up. If you don't have an account, you can sign up for free at MongoDB Atlas. Once you have an account, follow the Getting Started guide to set up a minimum free tier cluster. Initial configuration Obtain your connection string Once the MongoDB Atlas cluster is set up, locate your newly created cluster, click the "Connect" button, and select the "Compass" section. Copy the provided connection string. It should resemble something like this: mongodb+srv://:@cluster-name.xxxxx.mongodb.net/ Note: You will need the connection string to set up your environment variables later (MONGODB_URI). Cloning the GitHub repository Now, it's time to clone the demo app source code from GitHub to your local machine: Open your terminal or command prompt. Navigate to your preferred directory where you want to store the project using the cd command. For example: cd /path/to/your/desired/directory Once you're in the desired directory, use the git clone command to clone the repository. Copy the repository URL from the GitHub repository's main page: git clone git@github.com:mongodb-industry-solutions/inventory-management.git After running the git clone command, a new directory with the repository's name will be created in your chosen directory. To navigate into the cloned repository, use the cd command: cd inventory-management MongoDB Atlas configuration Replicate the sample database The database contains: Five collections Products: The sample database contains 17 products corresponding to T-shirts of different colors. Each product has five variants that represent five different sizes, from XS to XL. These variants are stored as an embedded array inside the product. Each variant will have a different SKU and therefore, its own stock level. Stock is stored both at item (items.stock) and product level (total_stock_sum). Transactions: This collection will be empty initially. Transactions will be generated using the app, and they can be of inbound or outbound type. Outbound transactions result in a decrease in the product stock such as a sale. On the other hand, inbound transactions result in a product stock increase, such as a replenishment order. Locations: Thi

This tutorial was written by Rami Pinto.
In the competitive retail landscape, having the right stock in the right place at the right time is crucial. Too little inventory when and where it’s needed can create unhappy customers. However, a large inventory can increase costs and risks associated with its storage. Companies of all sizes struggle with inventory management. Solutions such as a single view of inventory, real-time analytics, and event-driven architectures can help your businesses overcome these challenges and take your inventory management to the next level. By the end of this guide, you'll have inventory management up and running, capable of all the solutions mentioned above.
We will walk you through the process of configuring and using MongoDB Atlas as your back end for your Next.js app, a powerful framework for building modern web applications with React.
The architecture we're about to set up is depicted in the diagram below:
This will result in a multi-store inventory management solution capable of efficiently navigating through your product catalog, receiving alerts, and automating restock workflows, all while maintaining control of your inventory through real-time analytics. Check out the end result here.
Let's get started!
Prerequisites
Before you begin working with this project, ensure that you have the following prerequisites set up in your development environment:
- Git (version 2.39 or higher): This project utilizes Git for version control. Make sure you have Git installed on your system. You can download and install the latest version of Git from the official website: Git Downloads.
- Node.js (version 20 or higher) and npm (version 9.6 or higher): The project relies on the Node.js runtime environment and npm (Node Package Manager) to manage dependencies and run scripts. You need to have them both installed on your machine. You can download Node.js from the official website: Node.js Downloads. After installing Node.js, npm will be available by default.
-
mongorestore (version 100.9.4 or higher): The mongorestore tool loads data from a binary database dump. The dump directory in the GitHub repository includes a demo database with preloaded collections, views, and indexes, to get you up and running in no time. This tool is part of the MongoDB Database Tools package. Follow the Database Tools Installation Guide to install
mongorestore
. When you are done with the installation, runmongorestore --version
in your terminal to verify the tool is ready to use. - MongoDB Atlas cluster (M0 or higher): This project uses a MongoDB Atlas cluster to manage the database. You should have a MongoDB Atlas account and a minimum free tier cluster set up. If you don't have an account, you can sign up for free at MongoDB Atlas. Once you have an account, follow the Getting Started guide to set up a minimum free tier cluster.
Initial configuration
Obtain your connection string
Once the MongoDB Atlas cluster is set up, locate your newly created cluster, click the "Connect" button, and select the "Compass" section. Copy the provided connection string. It should resemble something like this:
mongodb+srv://:@cluster-name.xxxxx.mongodb.net/
Note: You will need the connection string to set up your environment variables later (MONGODB_URI
).
Cloning the GitHub repository
Now, it's time to clone the demo app source code from GitHub to your local machine:
Open your terminal or command prompt.
Navigate to your preferred directory where you want to store the project using the cd command. For example:
cd /path/to/your/desired/directory
- Once you're in the desired directory, use the git clone command to clone the repository. Copy the repository URL from the GitHub repository's main page:
git clone git@github.com:mongodb-industry-solutions/inventory-management.git
- After running the git clone command, a new directory with the repository's name will be created in your chosen directory. To navigate into the cloned repository, use the cd command:
cd inventory-management
MongoDB Atlas configuration
Replicate the sample database
The database contains:
- Five collections
Products: The sample database contains 17 products corresponding to T-shirts of different colors. Each product has five variants that represent five different sizes, from XS to XL. These variants are stored as an embedded array inside the product. Each variant will have a different SKU and therefore, its own stock level. Stock is stored both at item (items.stock
) and product level (total_stock_sum
).
Transactions: This collection will be empty initially. Transactions will be generated using the app, and they can be of inbound or outbound type. Outbound transactions result in a decrease in the product stock such as a sale. On the other hand, inbound transactions result in a product stock increase, such as a replenishment order.
Locations: This collection stores details of each of the locations where we want to keep track of the product stock. For the sake of this guide, we will just have two stores to demonstrate a multi-store scenario, but this could be scaled to thousands of locations. Warehouses and other intermediate locations could be also included. In this case, we assume a single warehouse, and therefore, we don’t need to include a location record for it.
Users: Our app will have three users: two store managers and one area manager. Store managers will be in charge of the inventory for each of the store locations. Both stores are part of the same area, and the area manager will have an overview of the inventory in all stores assigned to the area.
Counters: This support collection will keep track of the number of documents in the transactions collection so an auto-increment number can be assigned to each transaction. In this way, apart from the default _id
field, we can have a human-readable transaction identifier.
- One view:
Product area view: This view is used by the area manager to have an overview of the inventory in the area. Using the aggregation pipeline, the product and item stock levels are grouped for all the locations in the same area.
- One index:
The number of transactions can grow quickly as we use the app. To improve performance, it is a good practice to set indexes that can be leveraged by common queries. In this case, the latest transactions are usually more relevant and therefore, they are displayed first. We also tend to filter them by type—inbound/outbound—and product. These three fields—placement_timestamp
, type
, and product.name
—are part of a compound index that will help us to improve transaction retrieval time.
To replicate the sample database on your MongoDB Atlas cluster, run the following command in your terminal:
mongorestore --uri utils/dump/
Make sure to replace
with your MongoDB Atlas connection string. If you've already followed the initial configuration steps, you should have obtained this connection string. Ensure that the URI includes the username, password, and cluster details.
After executing these commands, you can verify the successful restoration of the demo database by checking the last line of the command output, which should display "22 document(s) restored successfully." These correspond to the 17 products, three users, and two locations mentioned earlier.
Note: You will need the database name to set up your environment variables later (MONGODB_DATABASE_NAME
). If the database name has not been specified, the default name will be inventory_management_demo
.
Set up Atlas Search and filter facets
Follow these steps to configure search indexes for full-text search and filter facets:
Navigate to the "Search & Vector Search" section within Atlas. Select your cluster and click on "Go to Atlas Search."
If you are in the M0 tier, you can create two search indexes for the products collection. This will allow you to merely search across the products collection. However, if you have a tier above M0, you can create additional search indexes. This will come in handy if you want to search and filter not only across your product catalog but also your transaction records, such as sales and replenishment orders.
Let's begin with creating the indexes for full-text search:
Click "Create Search Index."
Select “Atlas Search” as the search type, leave the index name as
default
, and choose "JSON Editor" as the Configuration Method. Then, click "Next."Select your newly created database and choose the products collection. We will leave the default index definition, which should look like the one below.
{
"mappings": {
"dynamic": true
}
}
- Click "Next" and on the next screen, confirm by clicking "Create Search Index."
- After a few moments, your index will be ready for use. While you wait, you can create the other search index for the
transactions
collection. You need to repeat the same process but change the selected collection in the "Database and Collection" menu next to the JSON Editor.
Important: The name of the index (default
) must be the same in order for the application to be able to work properly.
- Now, let's proceed to create the indexes required for the filter facets. Note that this process is slightly different from creating default search indexes:
- Click "Create Index" again, select Atlas Search and JSON Editor, and click "Next."
- Name this index
facets
. - Select your database and the products collection. For the index definition, paste the code below.
Facets index definition for products
{
"mappings": {
"dynamic": false,
"fields": {
"items": {
"fields": {
"name": {
"type": "stringFacet"
}
},
"type": "document"
},
"name": {
"type": "stringFacet"
}
}
}
}
- Click "Next" and confirm by clicking "Create Search Index." The indexing process will take some time. You can create the transactions index while waiting for the indexing to complete. In order to do that, just repeat the process but change the selected collection and the index definition by the one below:
Facets index definition for transactions
{
"mappings": {
"dynamic": false,
"fields": {
"items": {
"fields": {
"name": {
"type": "stringFacet"
},
"product": {
"fields": {
"name": {
"type": "stringFacet"
}
},
"type": "document"
}
},
"type": "document"
}
}
}
}
Important: The name of the index (facets
) must be the same in order for the application to be able to work properly.
By setting up these search indexes and filter facets, your application will gain powerful search and filtering capabilities, making it more user-friendly and efficient in managing inventory data.
Set up the Database Triggers
You will need to configure two database triggers. One will be used to enable autoreplenishment and the other to simulate item deliveries.
Autoreplenishment Trigger
Automate inventory replenishment by setting up a database trigger in MongoDB Atlas. Check how the stock is automatically replenished when a low-stock event occurs.
Follow these steps to enable the trigger:
Navigate to the "Triggers" section within the “Services" group in the left side menu in Atlas. For first-time users of Triggers, select your data source and then click “get started”. For non-first-time users, simply select "Add Trigger".
Choose the trigger type as "Database". Under “Trigger Source Details”, provide a name for the trigger and select your cluster, database, and the products collection. Set the operation type to "Update" only. Ensure that both "Full Document" and "Document Preimage" are enabled.
In the "Function" section, replace the default code with the code available at utils/triggers/autoreplenish.js in the cloned repository.
Open the "Advanced" section and insert the following code into the "Match Expression" field. This expression will ensure that the trigger function is executed only for products marked for auto-replenishment:
{
"fullDocument.autoreplenishment": true
}
- Verify that all the configuration details are accurate and click "Save."
For additional assistance, you can refer to the official documentation on how to create a database trigger.
Simulate Item Delivery Trigger
For a more realistic demo, we will set up another trigger that will wait the estimated delivery time of a particular item before recording it as delivered. Additionally, this trigger will automatically increment order numbers so we can have a numeric identifier of each order in addition to the unique _id
. To achieve this, follow these steps:
Just as in the previous step, navigate to the "Triggers" section. Create a new trigger by clicking "Add Trigger". Then choose the trigger type as "Database". Under “Trigger Source Details”, provide a name for the trigger and select your cluster, database, and the transactions collection. Set the operation type to "Insert" only. Ensure that "Full Document" is enabled.
The customized function for this trigger can be accessed at utils/triggers/issueInboundTransaction.js in the cloned repository.
Set up Atlas Charts
Enhance your application's visualization and analytics capabilities with Atlas Charts. Follow these steps to set up two dashboards — one for product information and another for general analytics. Let's begin by creating the product dashboard.
Navigate to the "Visualization" section located in the left side menu. Click the down arrow next to "Add Dashboard", then click "Import Dashboard".
Select one of the files from the /utils/charts folder in your cloned repository and click "Next". This folder contains exports to replicate dashboards tailored for each industry use case, retail or manufacturing. It also includes exports for the product and general dashboards, select one of them, follow the process below, and then repeat for the other one.
Click on the pencil icon and ensure the database is correctly assigned to the one previously created. Click "Save", and then "Save" again.
Then, click on the three dots in the top right corner of the newly created dashboard, and select "Embed". Check the "Enable unauthenticated access" option. In the "Allowed filter fields" section, edit the fields and select "Allow all fields in the data sources used in this dashboard". Choose the embedding method through the JavaScript SDK, and copy both the "Base URL" and the "Dashboard ID." Click “Close.”
Repeat the same process for the general dashboard. Note that the "Base URL" will be the same for both dashboards but the “dashboard ID” will be different so please take note of it.
(Optional) Personalize your charts! For detailed instructions visit the official Atlas Charts documentation.
Note: You will need the base URL and dashboard IDs to set up your environment variables later (CHARTS_EMBED_SDK_BASEURL
, DASHBOARD_ID_PRODUCT
, DASHBOARD_ID_GENERAL
).
Setting up Atlas Charts will provide you with visually appealing and insightful dashboards to monitor product information and overall analytics, enhancing your decision-making process and improving the efficiency of your inventory management system.
Frontend configuration
Set up environment variables
Copy the EXAMPLE.env
file in this directory to .env.local
(which will be ignored by Git), as seen below:
cp EXAMPLE.env .env.local
Now, open this file in your preferred text editor and update each variable on .env.local.
Remember all of the notes you took earlier? Grab them because you’ll use them now! Also, remember to remove any spaces after the equal sign.
MONGODB_URI
—This is your MongoDB connection string to MongoDB Atlas. You can find this by clicking the "Connect" button for your cluster. Note that you will have to input your Atlas password into the connection string.MONGODB_DATABASE_NAME
—This is your MongoDB database name for inventory management.CHARTS_EMBED_SDK_BASEURL
—This variable should hold the URL of the charts you want to embed in your application.DASHBOARD_ID_PRODUCT
—This variable should store the Atlas Charts dashboard ID for product information.DASHBOARD_ID_GENERAL
—This variable should store the Atlas Charts dashboard ID for the general analytics tab.DEMO_INDUSTRY
—For demo purposes, this variable will slightly change the UI based on the use case's industry focus. You can choose either retail or manufacturing.
Run locally
Execute the following commands to run your app locally:
npm ci
npm run dev
Your app should be up and running on http://localhost:3000! If it doesn't work, ensure that you have provided the correct environment variables.
Also, make sure your local IP is in the Access List of your project. If it’s not, just click the “Add IP address” button in the top right corner. This will display a popup menu. Within the menu, select “Add current IP address,” and click “Confirm.”
Enable real-time analytics
To create a general analytics dashboard based on sales, we will need to generate sales data. Navigate to the control panel in your app by clicking http://localhost:3000/control.
Then, click the “start selling” button. When you start selling, remember to not close this window as selling will only work when the window is open. This will simulate a sale every five seconds, so we recommend letting it run for a couple of minutes.
In the meantime, on a separate tab navigate to http://localhost:3000/dashboard. You will see live data coming in like in the chart below, offering you real-time insights!
Your app is ready to go! And this is just an example — feel free to add the charts you consider most useful to this dashboard.
Additional resources
Congratulations! Your inventory management app is ready to go. Throughout this tutorial, we’ve covered multiple MongoDB topics. Here’s a quick recap of the key learnings:
Real-time alerts: Implement real-time, low-stock alerts in your front end using Change Streams.
Workflow automation: Leverage database triggers to automate stock replenishment workflows.
Real-time analytics: Stay on top of your data, analyze trends, and make informed decisions in a timely manner thanks to Atlas Charts.
Single view of inventory: Take advantage of the flexibility of the document model to create a comprehensive single view of inventory.
Remember that this is just the beginning. Feel free to explore, tweak, and enhance your inventory management system to fit your own needs.
Curious for more? Learn how MongoDB is helping retailers to build modern consumer experiences. Check the additional resources below: