---
# System prepended metadata

title: GraphQL MongoDB Integration- Scaler Topics

---

---
title: GraphQL MongoDB Integration- Scaler Topics
description: With this article by Scaler Topics we will learn about graphQL MongoDB Integration with examples and explanations, read to know more.
category: MongoDB
author: Abantika Saha
---
:::section{.abstract}

## Overview
MongoDB is a popular NoSQL database that is used in many modern web applications for its `flexibility` and `scalability`. GraphQL is a more efficient, and flexible alternative to traditional RESTful APIs. Therefore, MongoDB GraphQL can provide developers with a faster and more adaptable way to access and manipulate data. GraphQL MongoDB can help developers create modern and powerful web applications that can handle the ever-increasing demands of today's users. 

:::

:::section{.main}

## Introduction to GraphQL
- GraphQL is a strongly-typed query language for APIs. It is a tool that describes data in` APIs,` allowing clients to request only what they require. It also makes updating APIs easier over time and provides useful developer tools.
- GraphQL has a `strongly-typed` schema that ensures only valid requests are made and errors are caught at compile time, reducing the number of requests required to retrieve data and improving performance.

![GraphQL logo](https://www.scaler.com/topics/images/graphol-logo.webp)

:::


:::section{.main}

## MongoDB Atlas GraphQL API
MongoDB GraphQL API interacts with data and serverless functions. You can also use the `GrapMongoDBoDB` API to call serverless functions that run custom logic on your data in response to events. Data can be retrieved and modified using this API by running complex queries, `mutations,` and subscriptions. `MongoDB GraphQL` API is customizable, thus allowing the developers to use their types and fields.

:::


:::section{.main}
## Operations
GraphQL MongoDB API allows interaction with data. The API allows for a wide range of operations such as queries, mutations, and subscriptions.  The `MongoDB GraphQL API enables the addition of new data, retrieval of existing data, and subscription to real-time updates, enabling applications to get updates as soon as data in the database changes.

To use the GraphQL MongoDB API, you must obtain a special code known as an API key and tell your program how to communicate with the MongoDB GraphQL service. To communicate with the MongoDB GraphQL service, you can use popular programming languages such as JavaScript, Java, or Python. Once your program is complete, you can start retrieving data from the database or adding new data to the database using MongoDB GraphQL API. It's a straightforward way of telling the database what information is required or what changes are needed.

![GraphQL operations](https://www.scaler.com/topics/images/graphql-operations.webp)
:::


:::section{.main}
## Queries
In `GraphQL MongoDB API`, the query operation is used to retrieve data from the MongoDB database. The query options help the users to retrieve data according to their needs, by providing filter and sort options.

For example,

**Find all the students who are currently studying in their 2nd year**
```javascript
query {
  students(
    query: {
      year: 2,
    }
  ) {
    _id
    name
    dept
    year
    cgpa
  }
}
```
Using MongoDB GraphQL API this query returns all students who are currently in 2nd year. It specifies that the year field should be 2. For each matching student, the query returns the id, name, dept, year, and cgpa fields.

**Find all students who have a CGPA greater than 9 and are of the Electrical Engineering Department**
```javascript
query {
  students(
    query: {
      cgpa: { $gt: 9 },
      dept: "Electrical Engineer"
    }
  ) {
    _id
    name
    dept
    year
    cgpa
  }
}
```
Using GraphQL MongoDB API, this query returns all students in the Electrical Engineering department with a CGPA greater than 9. It specifies that the cgpa field should be greater than 9 using the *$gt* operator and the dept field should be "Electrical Engineering". For each matching student, the query returns the id, name, dept, year, and cgpa fields.

:::


:::section{.main}
## Mutations
The mutation operation of MongoDB GraphQL API is used to modify data in the MongoDB database. It can be used to perform create, update, and delete operations.

For example,

**Create a new student record in the database with the specified name, dept, year, and cgpa fields.**

```javascript
mutation {
  createStudent(
    input: {
      name: "Dimple Roy",
      dept: "Electrical Engineering",
      year: 2,
      cgpa: 9.21
    }
  ) {
    _id
    name
    dept
    year
    cgpa
  }
}
```
Using GraphQL MongoDB API, this mutation adds a new student record to the database with the specified name, department, year, and cgpa. This is done using the createStudent mutation operation.

The mutation returns the `_id, name, dept, year, and cgpa` fields specified in the selection set for the newly created student record.

**Update the CGPA of the student with _id "201980020" to 9.5**

```javascript
mutation {
  updateStudent(
    input: {
      filter: { _id: "201980020" },
      set: { cgpa: 9.5 }
    }
  ) {
    _id
    name
    dept
    year
    cgpa
  }
}
```
Using MongoDB GraphQL API this mutation modifies the cgpa to 9.5 of students with _id equal to "201980020".
To perform the above task, the updateStudent mutation operation is used. The filter and set fields are passed through the input parameter for the update operation.

Based on the _id field, the filter field is used to identify which student record to update.

The set field is used to put the `new cgpa` value for the student. 

The mutation returns the updated student record fields: _id, name, dept, year, and cgpa, according to the selection set.

**Delete the student record with _id "201980020" from the database**

```javascript
mutation {
  deleteStudent(
    input: {
      filter: { _id: "201980020" }
    }
  ) {
    _id
    name
    dept
    year
    cgpa
  }
}
```
Using GraphQL `MongoDB API`, the deleteStudent mutation operation is used to delete the student with _id equal to "201980020" from the MongoDB database.

Based on the _id field, the filter field is used to specify which student record to delete. 

The mutation returns the deleted student record's _id, name, dept, year, and cgpa fields, according to the selection set. If the record has already been deleted, the response for all fields will be null.
:::


:::section{.main}
## Limitations
Some of the limitations of the MongoDB GraphQL API are:

- **Limited transaction operations support:** The ability of GraphQL MongoDB API is limited as it does not support all transaction options available in MongoDB.
- **Limited number of resolvers:** For any given query or mutation, the MongoDB GraphQL API can process up to ten actions called "resolvers" at once, and the entire operation fails with the error message "`max number of queries reached`" if this limit exceeds.
-  **Limited customization:** The simplicity and easy-to-use interface of GraphQL MongoDB API can limit the ability to customize the API for more complex operations.
- **Limitations of maximum relationship depth:** For a given query or mutation, the MongoDB GraphQL API can retrieve only a certain number of layers of data. This is known as "relationship depth". The API allows for a maximum depth of five layers. If you request information that exceeds this limit, the GraphQL MongoDB API will return an error message "`max relationship depth exceeded`". 
:::


:::section{.main}
## MongoDB GraphQL Server Techincal Preview

- MongoDB GraphQL Server Techincal Preview has been released by MongoDB.
- The `GraphQL MongoDB` server allows developers to build MongoDB GraphQL API which can interact with MongoDB data.
- It is made on top of the well-known graphql-js package.
- It communicates with the database using drivers written in the native language of MongoDB.
- Developers can create complicated queries and mutations to get and modify data, with ease using `GraphQL MongoDB` Server Technical Preview.
- Creating a query to fetch all students studying in a particular year, from the MongoDB database is an example use case.
:::


:::section{.main}
## Creating GraphQL API to Acess MongoDB Database
In this topic, we will be learning how to create a MongoDB GraphQL API with MongoDB and Apollo Server.

### Create a MongoDB Database using Mongo Atlas

![Creating a database in Mongo Atlas](https://www.scaler.com/topics/images/creating-a-database-in-mongo-atlas.webp)


- Log into your MongoDB Atlas account.
- Click "Build a Database" on the "Data Deployments" page.
- Select the deployment type and Cloud provider.
- Enter a cluster name and click "Create Cluster".
- Create a new user with the "Username & Password" authentication option.
- Add "0.0.0.0/0" to the IP Access List to allow access to your database.
- Click "`Finish and Close"`.
- Click  "Go to Databases", then "Connect" and copy the database connection string for later use.


### Project Setup

- We will create a folder named *studentGraphQL* and then install the necessary npm packages using the npm install command and create a subfolder *src*.
```javascript
npm install apollo-server graphql mongoose 
```
![Folder structure of the project setup in vscode](https://www.scaler.com/topics/images/folder-structure-of-the-project-setup-in-vscode.webp)

### Creating MongoDB Model

- Create a folder *models* inside *src*. Create a file named `student.js` inside `models` to store MongoDB schema.
```javascript
import mongoose from "mongoose";

export const Student = mongoose.model("Student", {
  name: String,
  dept: String,
  year: Number,
  cgpa: Number,
});
```

### Creating GraphQL Schema

- Create a `typeDefs.js` file inside `src` describing the GraphQL schema for the GraphQL server, which includes three types:
  1. Student
  2. Query 
  3. Mutation 
```javascript
import { gql } from "apollo-server";

export const typeDefs = gql`
  type Student {
    _id: ID!
    name: String!
    dept: String!
    year: Int!
    cgpa: Float!
  }

  type Query {
    getAllStudents: [Student!]!
  }

  type Mutation {
    createStudent(
      name: String!
      dept: String!
      year: Int!
      cgpa: Float!
    ): Student!
    deleteStudent(
      _id:ID!
    ): String!
    updateStudent(
      _id:ID!
      name: String
      dept: String
      year: Int
      cgpa: Float
    ): Student!
  }
`;
```

getAllStudents gives a list of all the student records present in the database.
 
![Testing getAllStudents query in GraphQL server](https://www.scaler.com/topics/images/testing-getallstudents-query-in-graphql-server.webp)

 
`createStudent` is used to create a student record with name, dept, year, and cgpa fields in the database. 
 
![Testing createStudent mutation in GraphQL server](https://www.scaler.com/topics/images/testing-createstudent-mutation-in-graphql-server.webp)
 
 ![MongoDB database displaying the newly created document](https://www.scaler.com/topics/images/mongodb-database-displaying-the-newly-created-document.webp)
 
`deleteStudent` is used to delete a student record according to a specified ID.
 
![Testing deleteStudent mutation in GraphQL server](https://www.scaler.com/topics/images/testing-deletestudent-mutation-in-graphql-server.webp)
  
updateStudent is used to update one or many fields of a student record.

 ![Testing updateStudent mutation in GraphQL server](https://www.scaler.com/topics/images/testing-updatestudent-mutation-in-graphql-server.webp)

- Create a file named `resolvers.js` which has resolver functions that carry out particular operations on the data source and provide the requested data in return.

```javascript
import { Student } from "./models/student.js";

export const resolvers = {
  Query: {
    getAllStudents: async (_root, _args, _context, _info) => {
      const data = await Student.find();
      return data;
    }
  },
  Mutation: {
    createStudent: (_root, args, _context, _info) => {
      const { name, dept, year, cgpa } = args
      const studentObj = new Student({
        name,
        dept,
        year,
        cgpa
      })
      return studentObj.save()
        .then(result => {
          return { ...result._doc }
        })
        .catch(err => {
          console.error(err)
        })
    },
    deleteStudent: async (_root, args, _context, _info) => {
      const { _id } = args;
      const deletedStudent = await Student.deleteOne({ _id: _id });
      return "Student removed from the database";
    },
    updateStudent:async (_root, args, _context, _info) => {
      const { _id} = args;
      const updatedStudent = await Student.findByIdAndUpdate({ _id: _id },
                                                             { $set: args }, 
                                                             { new: true });
      return updatedStudent;
    }
  }
}
```

### Creating GraphQL Server and Connecting it to the MongoDB Database

- The `resolver functions` and `typeDefs` need to be connected to a server. Therefore, we create an `index.js` file.
- We can connect to MongoDB using the connection string we obtained previously.

```javascript
import mongoose from "mongoose";
import { ApolloServer } from "apollo-server";

import { typeDefs } from "./typeDefs.js";
import { resolvers } from "./resolvers.js";

const uri =
  "mongodb+srv://<username>:<password>@cluster0.t7vkyke.mongodb.net/?retryWrites=true&w=majority";
const main = async () => {
  await mongoose. Connect(uri, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  });
};

main()
  .then(console.log("Connected to database successfully"))
  .catch((error) => console.error(error));

const server = new ApolloServer({ typeDefs, resolvers });

server.listen({ port: process.env.PORT || 4000 }).then(({ url }) => {
  console.log(`Server started at ${url}`);
});
```
Use the command *node index.js* to start the server.

In terminal:
``` javascript
node index.js
Connected to database successfully
The server started at http://localhost:4000/
```
Thus an instance of Apollo Server is created and launched on port `4000.`

![Instance of Apollo Server](https://www.scaler.com/topics/images/instance-of-apollo-server.webp)
:::


:::section{.faq-section}
## FAQs
**Q:** Can I use MongoDB GraphQL with different programming languages?

**A:** Yes, MongoDB GraphQL can be used with any programming language that supports GraphQL like `JavaScript`,` Python`, Java, etc. 

**Q:** Is GraphQL MongoDB production-ready?

**A:** `GraphQL MongoDB` is still under technical preview, therefore not ready for production use. However, MongoDB is working to make it available for use in production shortly.

**Q:**. How is GraphQL more advantageous than Rest API?

**A:** GraphQL has many advantages over `Rest API`. Some of them are:
- GraphQL is faster.
- `GraphQL avoids` the problems of `over-fetching` and under-fetching data.


**Q:** Can I use MongoDB GraphQL with real-time data?

**A:** Yes, MongoDB GraphQL provides real-time data synchronization.
:::


:::section{.summary}
## Conclusion
1. Use of `GraphQL MongoDB` together provides an easy and organized way for clients to query the data and gives the developers a great model to store and get data.
2. The developers can retrieve and manipulate data in real-time using queries, mutation, and subscription operations of the MongoDB` GraphQL API`.
3. The GraphQL MongoDB Server Technical Preview simplifies the development process by helping developers effortlessly create a GraphQL API for their MongoDB data.
4. Developers can build a MongoDB GraphQL API to access the MongoDB database, which helps to retrieve and handle data in an optimized way.
:::
