API Reference - mongodb/mlab-data-api GitHub Wiki

Overview

API Authentication

Each API request must pass an apiKey query parameter with the API key as defined in the MLAB_DATA_API_KEY environment variable of the running API service, for example:

/api/1/clusters?apiKey=2E81PUmPFI84t7UIc_5YdldAp1ruUPKye
Your API key, including any clients from which your API key can be recovered, should not be distributed to non-administrators.

Base URL Path

All API paths listed below are relative to the following base URL path:

<HOST>/api/1

Where <HOST> is the DNS address and port of the host serving your instance of the API service.

API Reference

Please note that the mLab Data API uses MongoDB Extended JSON in strict mode to encode queries and documents.

List clusters

To get a list of the clusters configured in the service:

GET /clusters

Example:
<HOST>/api/1/clusters?apiKey=<API_KEY>
Your API key, including any clients from which your API key can be recovered, should not be distributed to non-administrators.

List databases

To get a list of the databases configured in the service:

GET /databases

Example:
<HOST>/api/1/databases?apiKey=<API_KEY>
Your API key, including any clients from which your API key can be recovered, should not be distributed to non-administrators.

To get all the databases that a cluster connection has access to:

GET /clusters/{cluster}/databases

Example:
<HOST>/api/1/clusters/{cluster}/databases?apiKey=<API_KEY>
Your API key, including any clients from which your API key can be recovered, should not be distributed to non-administrators.

List collections

To get the collections in the specified database:

GET /clusters/{cluster}/databases/{database}/collections
GET /databases/{database}/collections

Example:
<HOST>/api/1/clusters/{cluster}/databases/my-db/collections?apiKey=<API_KEY>
Your API key, including any clients from which your API key can be recovered, should not be distributed to non-administrators.

List documents

To get the documents in the specified collection. If no parameters are passed, it lists all of them. Otherwise, it lists the documents in the collection matching the specified parameters:

GET /clusters/{cluster}/databases/{database}/collections/{collection}
GET /databases/{database}/collections/{collection}

Example listing all documents in a given collection:
<HOST>/api/1/clusters/{cluster}/databases/my-db/collections/my-coll?apiKey=<API_KEY>

Optional parameters
[q=<query>][&c=true][&f=<fields>][&fo=true][&s=<order>][&sk=<skip>][&l=<limit>]
Your API key, including any clients from which your API key can be recovered, should not be distributed to non-administrators.

Optional parameters (MongoDB reference):

  • q=<query> - restrict results by the specified JSON query
  • c=true - return the result count for this query
  • f=<set of fields> - specify the set of fields to include or exclude in each document (1 - include; 0 - exclude)
  • fo=true - return a single document from the result set (same as findOne() using the mongo shell
  • s=<sort order> - specify the order in which to sort each specified field (1- ascending; -1 - descending)
  • sk=<num results to skip> - specify the number of results to skip in the result set; useful for paging
  • l=<limit> - specify the limit for the number of results (default is 1000)

Examples using these parameters:

"q" example - return all documents with "active" field of true:
<HOST>/api/1/clusters/{cluster}/databases/my-db/collections/my-coll?q={"active": true}&apiKey=<API_KEY>

"c" example - return the count of documents with "active" of true:
<HOST>/api/1/clusters/{cluster}/databases/my-db/collections/my-coll?q={"active": true}&c=true&apiKey=<API_KEY>

"f" example (include) - return all documents but include only the "firstName" and "lastName" fields:
<HOST>/api/1/clusters/{cluster}/databases/my-db/collections/my-coll?f={"firstName": 1, "lastName": 1}&apiKey=<API_KEY>

"f" example (exclude) - return all documents but exclude the "notes" field:
<HOST>/api/1/clusters/{cluster}/databases/my-db/collections/my-coll?f={"notes": 0}&apiKey=<API_KEY>

"fo" example - return a single document matching "active" field of true:
<HOST>/api/1/clusters/{cluster}/databases/my-db/collections/my-coll?q={"active": true}&fo=true&apiKey=<API_KEY>

"s" example - return all documents sorted by "priority" ascending and "difficulty" descending:
 <HOST>/api/1/clusters/{cluster}/databases/my-db/collections/my-coll?s={"priority": 1, "difficulty": -1}&apiKey=<API_KEY>

"sk" and "l" example - sort by "name" ascending and return 10 documents after skipping 20
 <HOST>/api/1/clusters/{cluster}/databases/my-db/collections/my-coll?s={"name":1}&sk=20&l=10&apiKey=<API_KEY>
Your API key, including any clients from which your API key can be recovered, should not be distributed to non-administrators.

Date example using extended json format with ISO-8601 date format:

<HOST>/api/1/clusters/{cluster}/databases/my-db/collections/my-coll?q={"date": {"$gt": {"$date": "2017-07-20T23:23:50Z"}, "$lt": {"$date": "2017-08-20T23:23:50Z"}}}&apiKey=<API_KEY>
Your API key, including any clients from which your API key can be recovered, should not be distributed to non-administrators.

Create collection

To create a new collection, just start using it! Just like using a standard driver or the shell, collections are created implicitly just by using them. As soon as you POST your first document you should see the collection appear.

Insert document

To create a new document in the specified collection:

POST /clusters/{cluster}/databases/{database}/collections/{collection}
POST /databases/{database}/collections/{collection}
Content-Type: application/json
Body: <JSON data>

Example (using jQuery):

$.ajax( { url: "<HOST>/api/1/clusters/{cluster}/databases/my-db/collections/my-coll?apiKey=<API_KEY>",
		  data: JSON.stringify( { "x" : 1 } ),
		  type: "POST",
		  contentType: "application/json" } );
Your API key, including any clients from which your API key can be recovered, should not be distributed to non-administrators.

If you POST a document that contains an _id field, the effect will be to overwrite any existing document with that _id. When your document already includes an _id value, think of POST like "save" or "upsert" (discussed below) rather than "create" or "insert".

One consequence of this behavior: for a document with an _id specified, there is no straightforward way in the API to realize a pure "insert" — that is, an operation that refuses to modify a pre-existing document with that _id. POST will save over the old document; PUT will modify it. If this property is problematic for your application, consider using a field other than _id, with its own index to enforce uniqueness.

Insert multiple documents

To add multiple documents to the specified collection, specify a list of documents in the data payload:

POST /clusters/{cluster}/databases/{database}/collections/{collection}
POST /databases/{database}/collections/{collection}
Content-Type: application/json
Body: <JSON data>

Example (using jQuery):

$.ajax( { url: "<HOST>/api/1/clusters/{cluster}/databases/my-db/collections/my-coll?apiKey=<API_KEY>",
		  data: JSON.stringify( [ { "x" : 1 }, { "x" : 2 }, { "x" : 3 } ] ),
		  type: "POST",
		  contentType: "application/json" } );
Your API key, including any clients from which your API key can be recovered, should not be distributed to non-administrators.

Update multiple documents

To update one or more documents in the specified collection, use a PUT request with a replacement document or update modifiers in the body (MongoDB reference):

PUT /clusters/{cluster}/databases/{database}/collections/{collection}
PUT /databases/{database}/collections/{collection}
Content-Type: application/json
Body: <JSON data>

Example setting "x" to 3 in the document with "_id" = 1234 (using jQuery):

$.ajax( { url: '<HOST>/api/1/clusters/{cluster}/databases/my-db/collections/my-coll?apiKey=<API_KEY>&q={"_id":1234}',
		  data: JSON.stringify( { "$set" : { "x" : 3 } } ),
		  type: "PUT",
		  contentType: "application/json" } );

Optional parameters:
[q=<query>][&m=true][&u=true]
Your API key, including any clients from which your API key can be recovered, should not be distributed to non-administrators.

Optional parameters:

  • q=<query> - only update document(s) matching the specified JSON query
  • m=true - update all documents collection or query (if specified). By default only one document is modified
  • u=true - "upsert": insert the document defined in the request body if none match the specified query

So, you can think of PUT like "update"; with u=true added, it becomes "update or insert", or "upsert" for short.

Delete/replace multiple documents

To replace the contents of some or all of a collection, use a PUT request with a replacement list of documents in the body. An optional query in the q parameter can be used to replace a subset of the collection. Specifying an empty list in the body is equivalent to deleting the documents matching the query.

PUT /clusters/{cluster}/databases/{database}/collections/{collection}
PUT /databases/{database}/collections/{collection}
Content-Type: application/json
Body: <JSON data>

Example (using jQuery):

$.ajax( { url: '<HOST>/api/1/clusters/{cluster}/databases/my-db/collections/my-coll?apiKey=<API_KEY>',
		  data: JSON.stringify( [ { "x" : 1 }, { "x" : 2 }, { "x" : 3 } ] ),
		  type: "PUT",
		  contentType: "application/json" } );

Optional parameters:
[q=<query>]
Your API key, including any clients from which your API key can be recovered, should not be distributed to non-administrators.

Optional parameters:

  • q=<query> - only replace the document(s) matching the specified JSON query

View, update or delete a single document

Returns the document with the specified _id:

GET /clusters/{cluster}/databases/{database}/collections/{collection}/{_id}
GET /databases/{database}/collections/{collection}/{_id}

Example:
<HOST>/api/1/clusters/{cluster}/databases/my-db/collections/my-coll/4e7315a65e4ce91f885b7dde?apiKey=<API_KEY>
Your API key, including any clients from which your API key can be recovered, should not be distributed to non-administrators.

Modifies the document matching the specified _id. If no document matching the specified _id already exists, it creates a new document. The data payload should contain a replacement document or update modifiers (MongoDB reference):

PUT /clusters/{cluster}/databases/{database}/collections/{collection}/{_id}
PUT /databases/{database}/collections/{collection}/{_id}
Content-Type: application/json
Body: <JSON data>

Example replace the matching document with { "x" : 2 } (using jQuery):

$.ajax( { url: "<HOST>/api/1/clusters/{cluster}/databases/my-db/collections/my-coll/4e7315a65e4ce91f885b7dde?apiKey=<API_KEY>",
		  data: JSON.stringify( { "x" : 2 } ),
		  type: "PUT",
		  contentType: "application/json" } );

Example setting "y" to 5 in the matching document without affecting other fields (using jQuery):

$.ajax( { url: "<HOST>/clusters/{cluster}/api/1/databases/my-db/collections/my-coll/4e7315a65e4ce91f885b7dde?apiKey=<API_KEY>",
		  data: JSON.stringify( { "$set" : { "y" : 5 } } ),
		  type: "PUT",
		  contentType: "application/json" } );
Your API key, including any clients from which your API key can be recovered, should not be distributed to non-administrators.

Deletes the document with the specified _id:

DELETE /clusters/{cluster}/databases/{database}/collections/{collection}/{_id}
DELETE /databases/{database}/collections/{collection}/{_id}

Example (using cURL):
curl -X DELETE '<HOST>/api/1/clusters/{cluster}/databases/my-db/collections/my-coll/4e7315a65e4ce91f885b7dde?apiKey=<API_KEY>

Example (using jQuery):

$.ajax( { url: "<HOST>/api/1/clusters/{cluster}/databases/my-db/collections/my-coll/4e7315a65e4ce91f885b7dde?apiKey=<API_KEY>",
		  type: "DELETE",
		  async: true,
		  timeout: 300000,
		  success: function (data) { },
		  error: function (xhr, status, err) { } } );
Your API key, including any clients from which your API key can be recovered, should not be distributed to non-administrators.

Run database and collection-level commands

To run a MongoDB database command, send a POST request to the runCommand endpoint. Only certain MongoDB commands are exposed through the Data API. If there are other commands you need to run, you can always use the mongo shell or a standard MongoDB driver instead. The available commands are:

  • getLastError
  • getPrevError
  • ping
  • profile
  • repairDatabase
  • whatsmyuri
  • aggregate
  • convertToCapped
  • distinct
  • findAndModify
  • geoNear
  • reIndex
  • collStats
  • dbStats
POST /clusters/{cluster}/databases/{database}/runCommand
POST /databases/{database}/runCommand
Content-Type: application/json
Body: <JSON data>

Example (using jQuery):
The following returns a list of distinct values for 'account' in the 'users' collection matching {"active": true}.

$.ajax( { url: "<HOST>/api/1/clusters/{cluster}/databases/my-db/runCommand?apiKey=<API_KEY>",
		  data: JSON.stringify( {"distinct": "users","key": "account","query": {"active":true}} ),
		  type: "POST",
		  contentType: "application/json",
		  success: function(msg) {
			   alert( msg );
		  } } )
Your API key, including any clients from which your API key can be recovered, should not be distributed to non-administrators.

HTML Status Codes

The API commonly returns the following codes. For further reference, see W3C's documentation.

200 - OK : Returned whenever a resource is listed, viewed, updated or deleted

201 - Created : Returned whenever a resource is created (instead of code 200) : Note: in version 1 of the API (i.e., resource paths beginning with /api/1), all successful operations return code 200, even when new resources have been created. However, future API versions will use this 201 code as described.

400 - Bad Request : Returned whenever a request cannot be fulfilled because of an error with the input

401 - Unauthorized : Returned either when no user credentials could be found or the credentials found are not authorized to perform the requested action

403 - Forbidden : Returned whenever the server is refusing access to a resource, usually because the user does not have permissions to it

404 - Not Found : Returned whenever the resource being requested does not exist

405 - Method Not Allowed : Returned whenever the HTTP method (e.g. GET or POST) is not supported for the resource being requested

UTF-8 Characters

The API does support UTF-8 characters. As per the HTTP spec, you need to be sure to explicitly set the character set you are using in the Content-Type header. The default character set (ISO-8859-1) is not very i18n friendly.

Here's an example of posting special characters using the UTF-8 character set.

POST /clusters/{cluster}/databases/{database}/collections/{collection}
POST /databases/{database}/collections/{collection}
Content-Type: application/json;charset=utf-8
Body: <JSON data>

Example (using jQuery):

$.ajax( { url: "<HOST>/api/1/clusters/{cluster}/databases/my-db/collections/my-coll?apiKey=<API_KEY>",
		  data: JSON.stringify( { "Iñtërnâtiônàlizætiøn" : true } ),
		  type: "POST",
		  contentType: "application/json;charset=utf-8" } );
Your API key, including any clients from which your API key can be recovered, should not be distributed to non-administrators.

Frequently Asked Questions (FAQ)

Q. How do I insert a date in a REST call?

Dates for use in MongoDB documents can be constructed as ISO UTC strings with special $date key. The field might look like:

{"myDate": {"$date": "2010-07-20T23:23:50Z"}}

So, a "book" document with a published_date might look like:

{"bookTitle": "How to insert dates",
 "publishedDate": {"$date": "2010-07-20T23:23:50Z"},
 "authorName": "Robert"}

If you're open to using a JavaScript Library, try DateJS. There's a Google resource that describes the methods of the DateSJ Date class, particularly the toISOString method. Here's an example:

$.ajax( { url: "<HOST>/api/1/clusters/{cluster}/databases/my-db/collections/my-coll?apiKey=<API_KEY>",
		  data: JSON.stringify({"lat": 41.23, "long": 2.23, "time": {"$date": new Date().toISOString()}}),
		  type: "POST",
		  contentType: "application/json" } );
Your API key, including any clients from which your API key can be recovered, should not be distributed to non-administrators.

Q. Does the Data API support MongoDB's aggregation framework?

Yes. You can use the aggregate command through the runCommand endpoint.

That said, as noted in the above Overview, we strongly recommend connecting directly to your database using a standard MongoDB driver if possible.

⚠️ **GitHub.com Fallback** ⚠️