HomeLearnHow-toMongoDB Atlas Serverless Instances: Quick Start

MongoDB Atlas Serverless Instances: Quick Start

Updated: Jul 19, 2021 |

Published: Jul 13, 2021

  • Atlas
  • JavaScript
  • Cloud
  • ...

By Jesse Hall

Rate this article

MongoDB Atlas serverless instances are now available in preview!

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.

#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".

https://mongodb-devhub-cms.s3.us-west-1.amazonaws.com/Screen_Shot_2021_07_16_at_3_52_21_PM_25c61de281.png

Next, choose the Serverless deployment option.

https://mongodb-devhub-cms.s3.us-west-1.amazonaws.com/Screen_Shot_2021_07_16_at_3_52_50_PM_203c12265e.png

Now, just 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!

https://mongodb-devhub-cms.s3.us-west-1.amazonaws.com/Screen_Shot_2021_07_16_at_3_55_23_PM_2ec017a847.png

Your serverless instance will be up and running in just a few minutes. 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.”

    https://mongodb-devhub-cms.s3.us-west-1.amazonaws.com/EXTERNAL_Cluster_Card_Close_Up_2x_38c2a5e381.png

  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.

    https://mongodb-devhub-cms.s3.us-west-1.amazonaws.com/EXTERNAL_Connect_to_Cluster_2x_eccf2b8761.png

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! Remember that serverless instances are in preview currently. That means that it is in the process of being battle-tested and is missing some capabilities of the tiered clusters. More features will be added over time.

We think that serverless instances are going to be a popular deployment option for new users on Atlas—but we need your help! If you are an early adopter, give a serverless instance a try in your next development project and help us test it out.

I’d love to hear your feedback or questions. Let’s chat in the MongoDB Community.

Rate this article
MongoDB Icon
  • Developer Hub
  • Documentation
  • University
  • Community Forums

© MongoDB, Inc.