/

hasura-header-illustration

A new framework for building and evolving your APIs for MongoDB

We are excited to announce the release of Hasura’s native data connector for MongoDB. With this connector, users are able to rapidly author extremely capable APIs for data stored in MongoDB using Hasura’s Data Delivery Network (DDN).

Hasura DDN represents a new framework for developing, operating, and maintaining your APIs as your domain and data consumption requirements evolve.

In the sections below, we’ll outline what goes into a good API for MongoDB, what it takes to build and maintain one, and how Hasura’s new framework allows developers to accelerate new projects and scale existing projects at a rapid pace.

What makes for a great API on MongoDB

Creating a great API on MongoDB involves integrating several key components that enhance functionality, usability, and performance. Here's a concise list of some of these essential elements:

  • Documentation
  • Type Safety
  • Versioning
  • Pagination, Filtering, Sorting
  • Ability to Query Nested Data
  • Joins
  • Authorization
  • Performance, Low Latency
  • Enabling MongoDB features such as Vector Search, Time Series, and others.

Streamlining API development with Hasura DDN

Hasura's Data Delivery Network (DDN) streamlines the creation of APIs for MongoDB by abstracting the complexities of MongoDB’s schema-less model and offering a more structured approach through its intuitive and declarative domain-first modeling framework. This enables backend teams to rapidly model data domains, permissions, and relationships using Hasura metadata, which automatically generates standardized API endpoints. This "configure, not code" methodology drastically reduces the development effort required to handle MongoDB's flexible, JSON-like documents.

Developers no longer need to manually craft and optimize complex queries to accommodate data variability, such as nested documents or arrays. Hasura DDN offers advanced features like cross-domain joins, nested filtering, and sorting right out of the box. These features, which are typically challenging and time-consuming to code, are now effortless, allowing developers to fetch, filter, and aggregate any shape of data on demand across a unified API.

The Hasura DDN framework for MongoDB

Hasura DDN's framework significantly accelerates the development and scaling of MongoDB APIs by providing tools that streamline schema generation, enhance documentation, ensure type safety, and facilitate complex queries while managing API evolution and maintaining robust security measures.

Auto generate schema and customization

When you connect MongoDB to Hasura, GraphQL schemas will be autogenerated for you based on a MongoDB JSON validation schema, if one is available, or by sampling documents to determine what the schema should be. This speeds up the development process and reduces the effort required to manage data consistency across your applications.

The auto generated schema is not just a static artifact – it's a dynamic starting point. Developers can refine this schema, add custom queries, or modify types as needed. This flexibility allows developers to tailor the GraphQL layer to fit their application requirements closely.

The Hasura Language Server Protocol (LSP) enables the integration of language features such as tracking data source objects, validation of metadata, providing diagnostics at the time of authoring, and helping autocomplete metadata. With LSP-assisted metadata authoring, API producers can intuitively and declaratively create relationships and permissions for models and functions.

Documentation and discovery

A great API must have comprehensive, clear, and easily accessible documentation. This should include detailed descriptions of all API endpoints, data models, authentication mechanisms, and example requests and responses. Good documentation not only makes the API user-friendly but also reduces the learning curve for developers.

With Hasura DDN for MongoDB, you instantly get a self-documented GraphQL API  and a searchable data graph of not only MongoDB but all data sources and business logic that are part of the API.

Using Hasura Console’s explorer UI, you can see a top-down view of your supergraph. Hasura DDN allows you to organize your data sources and business logic as domains so consumers better understand your data structure.

Users can search and drill down into specific models to see specific data types, relations, and permissions.

Querying nested data

MongoDB supports rich document structures, including nested documents and arrays. A great API should provide capabilities to efficiently query these nested structures, allowing users to retrieve comprehensive datasets in a structured manner.

Here is an abbreviated example of a document from the MongoDB-provided dataset sample_mflix.movies. You can see several examples of fields that arrays such as cast and directors as well as objects such as awards.

{
    "_id": {
        "$oid": "573a1390f29313caabcd5a93"
    },
    "plot": "Christ takes on the form of a pacifist count to end a senseless war.",
    "genres": [
        "Drama"
    ],
    "runtime": {
        "$numberInt": "78"
    },
    "cast": [
        "Howard C. Hickman",
        "Enid Markey",
        "Lola May",
        "Kate Bruce"
    ],

   ...

    "directors": [
        "Reginald Barker",
        "Thomas H. Ince",
        "Raymond B. West",
        "Walter Edwards",
        "David Hartford",
        "Jay Hunt",
        "J. Parker Read Jr."
    ],
    "writers": [
        "C. Gardner Sullivan"
    ],
    "awards": {
        "wins": {
            "$numberInt": "1"
        },
        "nominations": {
            "$numberInt": "0"
        },
        "text": "1 win."
    },
...
            }
        }
    }
}

Hasura’s auto generated API allows users to query data found in nested arrays or objects. Furthermore, users can specify what fields they want returned and the structure of the response.

For example, below you can see how an API consumer leverages the GraphQL explorer to return the arrays for directors and cast, and specifies that they only want to return the nomination and wins from the awards object.

Pagination, filtering, sorting

Including pagination, filtering, and sorting functionalities in a GraphQL API for MongoDB data is crucial for creating efficient and user-friendly APIs.

Pagination is particularly important because it controls the volume of data sent in a single response, preventing performance bottlenecks and enhancing the user experience by allowing data to be consumed in manageable chunks. Additionally, pagination helps reduce the load on the server and the client, optimizing the overall system performance and ensuring that applications remain responsive even under heavy loads. Together, pagination, filtering, and sorting not only improve the functionality and usability of an API but also significantly enhance the end-user experience by providing quick access to precise, organized data. These features are indispensable for developers building scalable, efficient, and highly functional APIs using MongoDB.

Here is one example of how you could paginate over groups of 10 movies ordered by release date:

Join collections

Although MongoDB is a NoSQL database, it offers the $lookup aggregation stage that acts like an SQL join. A well-designed API should leverage this to allow users to perform operations similar to joins, enhancing the query capabilities across different collections.

For example, take the sample_mflix sample dataset. There are comments posted by users about movies. There is a one-to-many relationship, between movies and comments and users and comments. Hasura makes it easy to configure relationships between documents.

API consumers are able to draft queries that return users or movies with their corresponding comments without needing to know how the data is stored and fetched. API producers can expand the capabilities of the API with confidence.

Despite being a NoSQL database, using MongoDB and Hasura together gives you the best of NoSQL and relational databases for both API producers and consumers.

Performance

The MongoDB connector builds efficient query plans using MongoDB aggregation pipelines. Setting aside remote joins, the connector can execute each GraphQL query using a single request to MongoDB. That includes queries with relations between collections in the same database, queries that reference native queries, and in the future queries that simultaneously perform aggregations and select document fields.

For example, here’s a GraphQL query based on the sample_mflix data set that uses Hasura’s data graph to follow a relationship from the “movies” to “comments”:

query {
  movies(limit:10) {
	title
	comments {
  	email
  	text
	}
  }
}

The MongoDB connector translates that GraphQL into this query plan:

db.movies.aggregate([
  {
    "$lookup": {
      "from": "comments",
      "localField": "_id",
      "foreignField": "movie_id",
      "pipeline": [
        {
          "$replaceWith": {
            "email": "$email",
            "text": "$text"
          }
        }
      ],
      "as": "comments"
    }
  },
  {
    "$limit": 10
  },
  {
    "$replaceWith": {
      "title": "$title",
      "comments": {
        "rows": {
          "$getField": {
            "$literal": "comments"
          }
        }
      }
    }
  }
])

Type safety

GraphQL's type system significantly enhances the development of APIs and applications using NoSQL databases like MongoDB, which inherently lack a strict schema.

By introducing a structured type system on top of the schemaless nature of NoSQL databases, GraphQL facilitates a more organized approach to data handling. This structure ensures that while the flexibility and utility of typeless systems are maintained, applications can still enforce a consistent, well-defined schema that evolves with the development process. This resolves the primary criticism from NoSQL opponents regarding the perceived regression to less structured database systems.

By leveraging GraphQL, developers can define clear and precise data structures, improving development efficiency and data integrity without sacrificing NoSQL databases' adaptability. This system bridges the gap between the flexibility of schemaless databases and the need for structured data representation, making it an ideal solution for modern, dynamic application development.

Versioning and API evolution

As your API evolves, you might need to update its structure to accommodate new features or improvements.

Direct modifications to the API, such as altering or removing fields in responses, can result in breaking changes that disrupt client applications. Hasura addresses this challenge by utilizing the @deprecated schema directive in GraphQL. This feature allows you to mark fields as deprecated and provide an optional reason, effectively notifying your API consumers about the changes without causing immediate disruptions.

Versioning helps maintain stability and backward compatibility as your API evolves. Learn more about API versioning through field deprecation.

Authorization

Hasura provides robust security and authorization features to ensure data access is strictly controlled and compliant with organizational policies. Here's how Hasura manages these crucial aspects:

  • Role-Based Access Control (RBAC): Efficiently manages user access rights within the API, ensuring users only see data they are authorized to access.
  • Row and Column Permissions: Hasura allows setting permissions that restrict access to specific rows or columns in the database, tailoring visibility based on user roles.
  • Flexible Authentication Integration: Supports integration with a variety of popular authentication services or custom solutions, allowing for versatile user authentication.
  • Granular Access Control via Session Variables: Utilizes session variables passed through JWT or webhooks from the authentication service to establish detailed access control rules, determining precisely what data users can access.

Learn more about Hasura DDN authentication and authorization.

Custom business logic

Hasura DDN allows for writing custom business logic using the Node.js Lambda Connector with TypeScript.

Users can expose generic functions or procedures that can be added to metadata as a command. This custom business logic can leverage the same relationship and permissions features available for collection making them an interconnected part of your API or supergraph.

Getting started connecting Hasura to MongoDB

Create a MongoDB project

If you don’t already have an Atlas MongoDB instance available, simply launch a free instance here. Luckily, Mongo provides a large library of sample data sets to help you get started.

For the examples below, we’ll use the sample_mflix dataset.

Connect to Hasura

Please refer to the Getting Started – Create an API documentation if you get stuck during the steps outlined below.

Prerequisites

  1. Install the new Hasura CLI – to quickly and easily create and manage your Hasura projects and builds.
  2. Install the Hasura VS Code extension – with support for other editors coming soon (recommended)!

Create project and connect to MongoDB

Login to Hasura Cloud with the CLI.

ddn login

Create a new project using the create project command in the CLI and change to the new directory that was generated.

ddn create project --dir ./my-first-supergraph
cd my-first-supergraph

Run the add connector-manifest command to create a connector for MongoDB in your project.

ddn add connector-manifest <connector name> --subgraph app --hub-connector hasura/mongodb --type cloud

Add your connection URL to: app/mongodb/connector/mongodb_connector.build.hml

kind: ConnectorManifest
version: v1
spec:
  supergraphManifests:
    - base
definition:
  name: mongodb_connector
  type: cloud
  connector:
    type: hub
    name: hasura/mongodb:v0.0.4
  deployments:
    - context: .
      env:
        MONGODB_DATABASE_URI:
          value: "<input your MongoDB connection string here>"

Update connector, track models, and build

Run the following commands to add specific models. In this example, the `Trips` table and `MonthlyRevenue` view will be added as models to your API.

ddn update connector-manifest mongodb_connector
ddn update data-connector-link mongodb_connector
ddn add model --data-connector-link mongodb_connector --name Movies
ddn build supergraph-manifest

Try some GraphQL queries

You are now ready to start using your API!

During the previous step, the console will return some information including the `Console URL`. Load this link in your browser to explore the API you have created for your MongoDB database.

The UI will resemble something like this:

Next steps

From here you can start adding relationships, permissions, mutations and more.
Start for free or book a demo!

02 May, 2024

9 MIN READ

Share
Blog
02 May, 2024
Email
Subscribe to stay up-to-date on all things Hasura. One newsletter, once a month.
Loading...
v3-pattern
Accelerate development and data access with radically reduced complexity.