0
0
GraphQLquery~10 mins

MongoDB with GraphQL

Choose your learning style9 modes available
Introduction

MongoDB stores data as flexible documents. GraphQL lets you ask for exactly the data you want. Using them together helps you get data easily and quickly.

You want to build a website that shows user profiles stored in MongoDB.
You need to fetch only some fields from a large MongoDB collection to save bandwidth.
You want to update MongoDB data through a simple API without writing many endpoints.
You want to combine data from MongoDB with other data sources in one query.
You want to let frontend developers ask for data without backend changes.
Syntax
GraphQL
type Query {
  getItems: [Item]
}

type Item {
  id: ID!
  name: String
  description: String
}

type Mutation {
  addItem(name: String!, description: String): Item
}

# Resolver example in JavaScript
const resolvers = {
  Query: {
    getItems: async () => {
      const items = await mongoCollection.find().toArray();
      return items.map(item => ({
        id: item._id.toString(),
        name: item.name,
        description: item.description
      }));
    }
  },
  Mutation: {
    addItem: async (_, { name, description }) => {
      const result = await mongoCollection.insertOne({ name, description });
      return {
        id: result.insertedId.toString(),
        name,
        description
      };
    }
  }
};

GraphQL schema defines what data you can ask for.

Resolvers connect GraphQL queries to MongoDB operations.

Examples
Fetch only id and name fields from MongoDB documents.
GraphQL
query {
  getItems {
    id
    name
  }
}
Fetch id and description fields instead.
GraphQL
query {
  getItems {
    id
    description
  }
}
Add a new item to MongoDB and get back its id and name.
GraphQL
mutation {
  addItem(name: "Book", description: "A nice book") {
    id
    name
  }
}
Sample Program

This program sets up a GraphQL server connected to MongoDB. It defines a query to get all items and a mutation to add a new item. It converts MongoDB's _id to string for GraphQL.

GraphQL
# GraphQL schema definition
const { ApolloServer, gql } = require('apollo-server');
const { MongoClient, ObjectId } = require('mongodb');

const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);

const typeDefs = gql`
  type Item {
    id: ID!
    name: String
    description: String
  }

  type Query {
    getItems: [Item]
  }

  type Mutation {
    addItem(name: String!, description: String): Item
  }
`;

async function startServer() {
  await client.connect();
  const db = client.db('testdb');
  const itemsCollection = db.collection('items');

  const resolvers = {
    Query: {
      getItems: async () => {
        const items = await itemsCollection.find().toArray();
        return items.map(item => ({
          id: item._id.toString(),
          name: item.name,
          description: item.description
        }));
      }
    },
    Mutation: {
      addItem: async (_, { name, description }) => {
        const result = await itemsCollection.insertOne({ name, description });
        return {
          id: result.insertedId.toString(),
          name,
          description
        };
      }
    }
  };

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

  server.listen().then(({ url }) => {
    console.log(`Server ready at ${url}`);
  });
}

startServer();
OutputSuccess
Important Notes

GraphQL queries let you ask for only the data you need, reducing data transfer.

Resolvers must convert MongoDB ObjectId to string for GraphQL ID type.

Use async/await to handle MongoDB calls inside resolvers.

Summary

MongoDB stores flexible documents; GraphQL queries them precisely.

Define GraphQL schema and resolvers to connect to MongoDB.

Use queries to fetch data and mutations to change data in MongoDB.