Explore Developer Center's New Chatbot! MongoDB AI Chatbot can be accessed at the top of your navigation to answer all your MongoDB questions.

Join us at AWS re:Invent 2024! Learn how to use MongoDB for AI use cases.
MongoDB Developer
Atlas
plus
Sign in to follow topics
MongoDB Developer Centerchevron-right
Developer Topicschevron-right
Productschevron-right
Atlaschevron-right

MongoDB Atlas Serverless Instances: Quick Start

Jesse Hall4 min read • Published Jul 13, 2021 • Updated Aug 13, 2024
ServerlessNode.jsAtlasJavaScript
Facebook Icontwitter iconlinkedin icon
Rate this quickstart
star-empty
star-empty
star-empty
star-empty
star-empty
MongoDB Atlas serverless instances are now GA (generally available)!
What is a serverless instance you might ask? In short, it’s an on-demand serverless database. In this article, we'll deploy a MongoDB Atlas serverless instance and perform some basic CRUD operations. You’ll need a MongoDB Atlas account. If you already have one sign-in, or register now.

Demand Planning

When you deploy a MongoDB Atlas cluster, you need to understand what compute and storage resources your application will require so that you pick the correct tier to accommodate its needs.
As your storage needs grow, you will need to adjust your cluster’s tier accordingly. You can also enable auto-scaling between a minimum and maximum tier.

Ongoing Management

Once you’ve set your tiering scale, what happens when your app explodes and gets tons of traffic and exceeds your estimated maximum tier? It’s going to be slow and unresponsive because there aren’t enough resources.
Or, maybe you’ve over-anticipated how much traffic your application would get but you’re not getting any traffic. You still have to pay for the resources even if they aren’t being utilized.
As your application scales, you are limited to these tiered increments but nothing in between.
These tiers tightly couple compute and storage with each other. You may not need 3TB of storage but you do need a lot of compute. So you’re forced into a tier that isn’t balanced to the needs of your application.

The Solve

MongoDB Atlas serverless instances solve all of these issues:
  • Deployment friction
  • Management overhead
  • Performance consequences
  • Paying for unused resources
  • Rigid data models
With MongoDB Atlas serverless instances, you will get seamless deployment and scaling, a reliable backend infrastructure, and an intuitive pricing model.
It’s even easier to deploy a serverless instance than it is to deploy a free cluster on MongoDB Atlas. All you have to do is choose a cloud provider and region. Once created, your serverless instance will seamlessly scale up and down as your application demand fluctuates.
The best part is you only pay for the compute and storage resources you use, leaving the operations to MongoDB’s best-in-class automation, including end-to-end security, continuous uptime, and regular backups.

Create Your First Serverless Instance

Let’s see how it works…
If you haven’t already signed up for a MongoDB Atlas account, go ahead and do that first, then select "Build a Database".
Next, choose the Serverless deployment option.
Now, select a cloud provider and region, and then optionally modify your instance name. Create your new deployment and you’re ready to start using your serverless instance!
Your serverless instance will be up and running in just a few minutes. Alternatively, you can also use the Atlas CLI to create and deploy a new serverless instance.
While we wait for that, let’s set up a quick Node.js application to test out the CRUD operations.

Node.js CRUD Example

Prerequisite: You will need Node.js installed on your computer.
Connecting to the serverless instance is just as easy as a tiered instance.
  1. Click “Connect.”
  2. Set your IP address and database user the same as you would a tiered instance.
  3. Choose a connection method.
    • You can choose between mongo shell, Compass, or “Connect your application” using MongoDB drivers.
We are going to “Connect your application” and choose Node.js as our driver. This will give us a connection string we can use in our Node.js application. Check the “Include full driver code example” box and copy the example to your clipboard.
To set up our application, open VS Code (or your editor of choice) in a blank folder. From the terminal, let’s initiate a project:
npm init -y
Now we’ll install MongoDB in our project:
npm i mongodb

Create

We’ll create a server.js file in the root and paste the code example we just copied.
1const MongoClient = require('mongodb').MongoClient;
2const uri = "mongodb+srv://mongo:<password>@serverlessinstance0.xsel4.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
3const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
4
5client.connect(err => {
6 const collection = client.db("test").collection("devices");
7
8 // perform actions on the collection object
9
10 client.close();
11});
We’ll need to replace <password> with our actual user password and myFirstDatabase with the database name we’ll be connecting to.
Let’s modify the client.connect method to create a database, collection, and insert a new document.
Now we’ll run this from our terminal using node server.
1client.connect((err) => {
2 const collection = client.db("store").collection("products");
3 collection
4 .insertOne(
5 {
6 name: "JavaScript T-Shirt",
7 category: "T-Shirts",
8 })
9 .then(() => {
10 client.close();
11 });
12});
When we use the .db and .collection methods, if the database and/or collection does not exist, it will be created. We also have to move the client.close method into a .then() after the .insertOne() promise has been returned. Alternatively, we could wrap this in an async function.
We can also insert multiple documents at the same time using .insertMany().
1collection
2 .insertMany([
3 {
4 name: "React T-Shirt",
5 category: "T-Shirts",
6 },
7 {
8 name: "Vue T-Shirt",
9 category: "T-Shirts",
10 }
11 ])
12 .then(() => {
13 client.close();
14 });
Make the changes and run node server again.

Read

Let’s see what’s in the database now. There should be three documents. The find() method will return all documents in the collection.
1client.connect((err) => {
2 const collection = client.db("store").collection("products");
3 collection.find().toArray((err, result) => console.log(result))
4 .then(() => {
5 client.close();
6 });
7});
When you run node server now, you should see all of the documents created in the console.
If we wanted to find a specific document, we could pass an object to the find() method, giving it something to look for.
1client.connect((err) => {
2 const collection = client.db("store").collection("products");
3 collection.find({name: React T-Shirt”}).toArray((err, result) => console.log(result))
4 .then(() => {
5 client.close();
6 });
7});

Update

To update a document, we can use the updateOne() method, passing it an object with the search parameters and information to update.
1client.connect((err) => {
2 const collection = client.db("store").collection("products");
3 collection.updateOne(
4 { name: "Awesome React T-Shirt" },
5 { $set: { name: "React T-Shirt" } }
6 )
7 .then(() => {
8 client.close();
9 });
10});
To see these changes, run a find() or findOne() again.

Delete

To delete something from the database, we can use the deleteOne() method. This is similar to find(). We just need to pass it an object for it to find and delete.
1client.connect((err) => {
2 const collection = client.db("store").collection("products");
3 collection.deleteOne({ name: "Vue T-Shirt" }).then(() => client.close());
4});

Conclusion

It’s super easy to use MongoDB Atlas serverless instances! You will get seamless deployment and scaling, a reliable backend infrastructure, and an intuitive pricing model. We think that serverless instances are a great deployment option for new users on Atlas.
I’d love to hear your feedback or questions. Let’s chat in the MongoDB Community.

Facebook Icontwitter iconlinkedin icon
Rate this quickstart
star-empty
star-empty
star-empty
star-empty
star-empty
Related
Article

Atlas Search Playground: Easy Experimentation


Jun 03, 2024 | 7 min read
Code Example

Blogue


Sep 11, 2024 | 1 min read
Article

Using Atlas Data Federation to Control Access to Your Analytics Node


Aug 28, 2024 | 9 min read
Tutorial

How to Build a RAG System Using Claude 3 Opus And MongoDB


Aug 28, 2024 | 15 min read
Table of Contents