Published on

MongoDB x Codeium

Written by
Codeium Team
MongoDB and Codeium.

We are excited to announce our partnership with MongoDB, where Codeium models are trained on MongoDB APIs and syntax in order to accelerate the development of MongoDB applications.

About MongoDB

MongoDB Atlas provides an integrated set of fully-managed database services that share a unified developer experience across transactional, analytical and generative AI apps. It allows developers to store and retrieve data in a flexible and scalable manner. It offers a document-oriented approach, where data is stored in JSON-like documents, making it easy to work with for developers. MongoDB's rich querying capabilities and horizontal scalability make it an excellent choice for modern applications that require flexibility and high-performance data storage.

So why a partnership with Codeium? MongoDB APIs are incredibly powerful, but due to the breadth and richness of the APIs, it is possible for developers to be spending more time than necessary looking through API documentation or using the APIs inefficiently for the task at hand. An AI assistant, if trained properly, can effectively assist the developer in retrieval and usage quality of these APIs. Since we at Codeium build our LLMs from scratch and own the data layer, unlike other AI code assistants, the possibility was ripe to accelerate and optimize the developer experience in unique and novel ways unmatched by others.

Getting Started with MongoDB and Codeium

All you need is to create an account on codeium.com and go to the download page to install Codeium's extension on your IDE of choice. After authenticating, you will passively receive autocomplete suggestions that will help accelerate you through your MongoDB application development.

Here, we will build a MongoDB application in VSCode using Codeium:

Check out the full demo video.

Let us walk through this step by step, and you can check out the demo repository to follow along: movie-reviews-sample-app

In this tutorial, we'll be setting up a web app to review movies. We'll be using NextJS and TailwindCSS, with our data store backed by MongoDB.

1. Clone the Starter Repo

Clone the starter repo: khou22/movie-reviews-sample-app.

To follow along, checkout the tutorial-init branch: git checkout tutorial-init.

Run our app which will hot reload throughout the duration of the tutorial:

yarn install
yarn dev

2. Setup Your MongoDB Project

First, you need to create a MongoDB Atlas account if you haven’t already. It’s free and quick to set up. Create a new MongoDB project (MongoDB Dashboard) and create a cluster in Atlas. We are calling ours movie-reviews-sample but you may use whatever you'd like.

Much like other databases (ie. Postgres, MySQL), we connect to MongoDB using a URI that contains credentials. Find and copy your URI and save it as an environment variable named MONGO_DB_URI in your .env.development.local. It'll look something like: mongodb+srv://<username>:<password>@<project_id>.mongodb.net.

# .env.development.local
MONGO_DB_URI="mongodb+srv://<username>:<password>@<project_id>.mongodb.net"

3. Use Codeium Context to Find API Endpoints

Because Codeium is codebase aware, it has knowledge over what files, functions, and docs are in your IDE's workspace. In addition to being trained on external libraries such as MongoDB, Codeium can intelligently decide when and where to look online for additional documentation.

With Codeium's search enabled (VS Code setting codeium.enableSearch), Codeium will index our repo to improve Autocomplete and Chat's personalization.

codeium search settings vscode

We can now ask Codeium Chat where we can implement our MongoDB integration:

Where do we store data in our database?

This will lead us to src/app/api/movie-review/route.ts which contains the GET and POST endpoints that we'll be using to retrieve and write reviews to the DB, respectively.

codeium mongodb chat context

4. Instruct Codeium to Integrate with MongoDB Writes

We will now setup the POST endpoint to write new movie review data to our MongoDB project. Codeium has read the MongoDB docs so that you don't have to! All we have to do now is write a comment describing what we'd like.

Right after instantiating the movieRecord object, we type our comment and press enter to start a suggestion on the newline:

// Connect to MongoDB and insert a new document.

This will suggest something like:

await client.connect();
const database = client.db(mongoDbId);
const collection = database.collection(mongoDbCollectionId);
await collection.insertOne(movieRecord);
client.close();
codeium mongodb autocomplete demo

We'll also want to wrap our business logic in a try / catch so that we can properly handle error states. Simply by typing try { above the MongoDB logic, Codeium will predict how to handle the catch:

codeium mongodb autocomplete context

Type as you would normally. With just a few suggestions and tabs, we'll end with something like this:

export async function POST(req: NextRequest) {
  const reqBody = (await req.json()) as NewMovieReviewRequest;
  const movieRecord: MovieReview = {
    id: crypto.randomUUID(),
    title: reqBody.title,
    review: reqBody.review,
    rating: reqBody.rating,
    imageUrl: reqBody.image_url,
    createdAt: new Date(),
  };

  const client = new MongoClient(uri);

  // Connect to MongoDB and insert a new document.
  try {
    await client.connect();
    const database = client.db(mongoDbId);
    const collection = database.collection(mongoDbCollectionId);
    await collection.insertOne(movieRecord);
    return new Response(JSON.stringify(movieRecord), { status: 200 });
  } catch (e) {
    console.error(e);
    if (e instanceof Error) {
      return new Response(e.message, { status: 500 });
    }
  } finally {
    client.close();
  }
}

5. Implement Reads from MongoDB

We'll now implement the read operations from MongoDB. It will be even easier now that Codeium has awareness of our schema (using the file as context for our AI generations).

In the GET endpoint, we'll again instruct Codeium using a comment:

// Read all movie reviews from my collection.

We'll get something like:

const database = client.db(mongoDbId);
const collection = database.collection(mongoDbCollectionId);
const movieRecords = await collection.find({}).toArray();

Make a few more changes, coding normally and accepting Codeium's suggestions:

  • Wrap everything in a try / catch
  • Transform the movieRecords document objects into our MovieRecords[] Typescript object.

At the end, we'll have something like:

export async function GET(_req: NextRequest) {
  const client = new MongoClient(uri);

  try {
    // Read all movie reviews from my collection.
    await client.connect();
    const database = client.db(mongoDbId);
    const collection = database.collection(mongoDbCollectionId);
    const movieRecords = await collection.find({}).toArray();

    const movies = movieRecords.map((movieRecord) => {
      return {
        id: movieRecord.id,
        title: movieRecord.title,
        review: movieRecord.review,
        rating: movieRecord.rating,
        imageUrl: movieRecord.imageUrl,
        createdAt: movieRecord.createdAt,
      };
    });
    const response: GetMoviesResponse = {
      reviews: movies,
    };

    return new Response(JSON.stringify(response), { status: 200 });
  } catch (e) {
    console.error(e);
    if (e instanceof Error) {
      return new Response(e.message, { status: 500 });
    }
  } finally {
    client.close();
  }
}

6. Add AI-Generated Function Docstrings with Codeium Chat

Codeium can also make it easier to keep your code well documented and adhering to best practices. You'll notice that Codeium adds AI code lenses above your code. On VSCode this looks like this:

codeium code lenses

7. Admire our Handywork

With both our GET and POST endpoints complete, our app is now complete.

codeium mongodb demo home
codeium mongodb demo form

You can checkout the main branch of the repo to see the completed code: movie-reviews-sample-app

Wrap-Up

In just a few short minutes (and significantly fewer keystrokes), we were able to implement a working MongoDB app! Best of all, we were able to do this entirely for free using MongoDB Atlas’ generous free tier and Codeium 100% free, forever individual plan.

Looking Forward

We look forward to deepening the quality of Codeium suggestions on the MongoDB Query API code and syntax, including its powerful and composable aggregation pipeline, used by developers for in-app data transformations and analytics. Any developer coding with MongoDB can use the Codeium extension for free using the individual plugin, and if this is interesting to you at the team or enterprise level, Codeium has tiers for that too.

Explore more

Jun 11, 2024enterprise7 min

A deeper dive into recent enterprise readiness capabilities: indexing access controls, subteam analy...

Apr 30, 2024enterprise1 min

WWT uses Codeium to accelerate their developers.

Apr 18, 2024company1 min

Codeium is the only AI code assistant in the 2024 Forbes AI 50 List.

Stay up to date on the latest Codeium & AI dev tool news

Please enter a valid email address