Interested in speaking at MongoDB World 2022? Click here to become a speaker.
HomeLearnQuickstartAn Introduction to the MongoDB Atlas Data API

An Introduction to the MongoDB Atlas Data API

Updated: Nov 25, 2021 |

Published: Nov 18, 2021

By John Page

Rate this article

#Introduction to the Data API

When MongoDB was first created, the way developers interacted with it was using language-specific drivers, libraries that converted seamlessly between language objects, and the MongoDB network protocol. Drivers also took care of connection pooling, authentication , failover, and marshalling of data to and from the BSON format stored in the database. This is still today the most popular way to use MongoDB but it's not the best choice for everyone.

With the introduction of MongoDB Atlas and Realm, we added the ability to write and host custom web service APIs as well as create GraphQL endpoints. Both of these allow connectivity without needing a driver but both also require a degree of server side configuration and coding and therefore are not accessible to everyone.

The MongoDB Atlas Data API provides a simple way to read and write data in MongoDB Atlas without requiring a driver library, providing the core of the driver's functions using JSON over HTTPS and allowing data access to MongoDB Atlas from a range of environments where a driver is either not possible or not practical.

This tutorial will show you how to enable the Data API and perform basic CRUD operations using cURL and Postman. It is the first in a series showing different uses for the Data API and how you can use it to build data-centric applications and services faster.

You can access the full API reference here.

This post assumes you already have an Atlas cluster. You can either use an existing one or you can sign up for a cloud account and create your first database cluster by following the instructions here.

#Enabling the Atlas Data API

Enabling the Data API is very easy once you have a cluster in Atlas.

First Click "Data API" in the bar on the left of your Atlas deployment.

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

Then select which data source or sources you want the Data API to have access to. For this example, we are selecting just the default Cluster0.

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

Then select the large "Enable the Data API" button.

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

You will then have a screen confirming what clusters you have enabled for the Data API.

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

Click on the button at the top left that says "Create API Key." https://mongodb-devhub-cms.s3.us-west-1.amazonaws.com/step5_b26eeda357.png

Finally, click "Generate API Key" and take a note of the key displayed in a secure place as you will not be able to see it again in Atlas. You can click the "Copy" button to copy it to your clipboard.

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

You are now ready to call the Data API.

In this first release, all authentication is with an API key which gives read and write to all databases and their collections in the selected cluster or clusters. Subsequent releases will have more sophisticated authentication and authorization models.

It is critically important with this early release to ensure end-users do not have access to the API key as they can modify or delete any of the data in the cluster. API keys should not be embedded in external applications or web pages where they can be extracted by a malicious user. The data API should only be used inside services or by trusted users.

#Calling the Data API

#Adding Some Data to Atlas

All the Data API endpoints use HTTPS POST. Though it might seem logical to use GET when reading data, GET requests are intended to be cached and many platforms will do so automatically. To ensure you never have stale query results, all of the API endpoints use POST.

To add documents to MongoDB, we use InsertOne or InsertMany.

#InsertOne

When we call the API, we state the cluster, database, collections, and content as part of a JSON payload document.

For authentication, we pass the API key as a header. The API always uses HTTPS, so this is safe and secure from network snooping.

To call with cURL, use the following command:

1curl https://data.mongodb-api.com/app/<Your AppId>/endpoint/data/beta/action/insertOne \
2-H 'Content-Type: application/json' \
3-H 'api-key: <Your API Key>' \
4--data-raw \
5'{
6 "dataSource": "<Your Cluster Name>",
7 "database" : "household",
8 "collection" : "pets",
9 "document" : { "name": "Harvest",
10 "breed": "Labrador",
11 "age": 5 }
12}'

For example, my call looks like this

1curl https://data.mongodb-api.com/app/dapi-qqwqe/endpoint/data/beta/action/insertOne \
2-H 'Content-Type: application/json' \
3-H 'api-key: XtjMmDf4e7bpLAlUYJhulrxZEIQXxG1UYcCrdvcgrw1YjIYVms9Hr4FVq3noqbeo' \
4--data-raw \
5'{
6 "dataSource": "Cluster0",
7 "database" : "household",
8 "collection" : "pets",
9 "document" : { "name": "Harvest",
10 "breed": "Labrador",
11 "age": 5 }
12}'
1{"insertedId":"618bce97527c32e056f93018"}

And as easily as that, we have added a new document to a collection called 'pets' in a database called 'houehold'. Due to MongoDB’s flexible dynamic model, neither the database nor collection needed to be defined in advance.

This API call returned a JSON document with the _id of the new document. As we didn't explicitly supply any value for _id ( the primary key in MongoDB), one was allocated for us and it was of type ObjectId: a 12-byte binary GUID. We are returning standard JSON so this is displayed as a string. It is critical when querying the database to wrap this string in an EJSON type as { "$oid" : <String Value> }. It will not match as a string as the data type is not a string in the database. In general, this only applied to automatically generated ObjectIds, so to retrieve this exact record with findOne, we would use:

1curl https://data.mongodb-api.com/app/<Your AppId>/endpoint/data/beta/action/findOne \
2-H 'Content-Type: application/json' \
3-H 'api-key: <Your API Key>' \
4--data-raw \
5'{
6 "dataSource": "<Your Cluster Name>",
7 "database" : "household",
8 "collection" : "pets",
9 "filter" : {"_id" : { "$oid" : "618bce97527c32e056f93018" }}
10}'

Running this shows us it has been added to the collection.

You can also explore this and the other examples here in Postman.

Run in Postman

To set up your API key and cluster id, click the eye icon at the top right and add two global variables apikey and appid with the values for your Atlas cluster. Persist the variables and save the page with Control+S, or Command+S on a Mac.

#InsertMany

We can add multiple documents at the same time by using insertMany and passing an array of documents.

1curl https://data.mongodb-api.com/app/<Your AppId>/endpoint/data/beta/action/insertMany \
2-H 'Content-Type: application/json' \
3-H 'api-key: <Your API Key>' \
4--data-raw \
5'{
6 "dataSource": "<Your Cluster Name>",
7 "database": "household",
8 "collection": "pets",
9 "documents": [{
10 "name": "Brea",
11 "breed": "Labrador",
12 "age": 9,
13 "colour": "black"
14 },
15 {
16 "name": "Bramble",
17 "breed": "Labrador",
18 "age": 1,
19 "colour": "black"
20 }
21 ]
22}'

Typical Output:

1{"insertedIds":["618bcea5329654eab7ea1fbe","618bcea5329654eab7ea1fbf"]}

Run in Postman

This will return us JSON with an array of the values for _id that were added.

#Retrieving Data with a Query

#find

Let's find all the labradors that are two years or older, sorted by age.

1curl https://data.mongodb-api.com/app/<Your AppId>/endpoint/data/beta/action/find \
2-H 'Content-Type: application/json' \
3-H 'api-key: <Your API Key>' \
4--data-raw \
5'{
6 "dataSource": "<Your Cluster Name>",
7 "database": "household",
8 "collection": "pets",
9 "filter": { "breed": "Labrador",
10 "age": { "$gt" : 2} },
11 "sort": { "age": 1 } }
12'

Typical Output:

1{"documents":[{"_id":"618bd214527c32e056fd4252","name":"Harvest","breed":"Labrador","age":5},{"_id":"618bd21a26f37209a62a43fc","name":"Brea","breed":"Labrador","age":9,"colour":"black"},{"_id":"618bd21a26f37209a62a43fd","name":"Bramble","breed":"Labrador","age":1,"colour":"black"}]}

Run in Postman

We are returned an object with a member 'documents' that is an array of everything that matched. If we want to fetch a subset of the results in pages, we can use the skip and limit parameter to set which result to start at and how many to return.

If we wanted only a single document, we could use the findOne endpoint instead.

#Modifying Existing Data

#UpdateOne

Harvest is a yellow labrador, so we can update her record to set this fact with updateOne.

1curl https://data.mongodb-api.com/app/<Your AppId>/endpoint/data/beta/action/updateOne \
2-H 'Content-Type: application/json' \
3-H 'api-key: <Your API Key>' \
4--data-raw \
5'{
6 "dataSource": "<Your Cluster Name>",
7 "database": "household",
8 "collection": "pets",
9 "filter" : { "name" : "Harvest"},
10 "update" : { "$set" : { "colour": "yellow" }}
11}'

Typical Output:

1{"matchedCount":1,"modifiedCount":1}

Run in Postman

From this, we get JSON returned telling us how many documents matched our filter and how many were then modified. In this case, we used updateOne, so even if multiple documents match, only one is changed. To change all matching documents, we would call updateMany with the same parameters.

#Run an Aggregation Pipeline to Compute Something

#aggregate

We can also run aggregation pipelines. As a simple example of how to call the aggregate endpoint, let's determine the count and average age for each colour of labrador.

1curl https://data.mongodb-api.com/app/<Your AppId>/endpoint/data/beta/action/aggregate \
2-H 'Content-Type: application/json' \
3-H 'api-key: <Your API Key>' \
4--data-raw \
5'{
6 "dataSource": "<Your Cluster Name>",
7 "database": "household",
8 "collection": "pets",
9 "pipeline" : [ { "$match": {"breed": "Labrador"}},
10 { "$group": { "_id" : "$colour",
11 "count" : { "$sum" : 1},
12 "average_age": {"$avg": "$age" }}}]}'

Typical output:

1{"documents":[{"_id":yellow,"count":1,"average_age":5},{"_id":"black","count":2,"average_age":5}]}

Run in Postman

This returns us two documents, one per colour showing the count and age. Aggregation pipelines are also used to run Atlas Search requests and return results if Atlas Searchis enabled.

#Next Steps

Hopefully, you now have all the information required to get started. If you are new to MongoDB, you can learn more about queries and documents here. If you just want to look at the API documentation, then it's here.

There are also more posts coming soon showing how to use the Data API to access MongoDB from a variety of environments where a driver is not the best option, including Google App Scripts, Microsoft Power Query, Amazon Lambda functions, and even Oracle PL-SQL.

Rate this article
MongoDB logo
© 2021 MongoDB, Inc.

About

  • Careers
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2021 MongoDB, Inc.