Compatibility: Only available on Node.js.You can still create API routes that use MongoDB with Next.js by setting the
runtime variable to nodejs like so:export const runtime = "nodejs";You can read more about Edge runtimes in the Next.js documentation here.Embeddings
This guide will also use OpenAI embeddings, which require you to install the@langchain/openai integration package. You can also use other supported embeddings models if you wish.
Installation
Install the following packages:Credentials
Once you’ve done the above, set theMONGODB_ATLAS_URI environment variable from the Connect button in Mongo’s dashboard. You’ll also need your DB name and collection name:
Instantiation
Once you’ve set up your cluster as shown above, you can initialize your vector store as follows:Manage vector store
Add items to vector store
You can now add documents to your vector store:id as an existing document will update the existing one.
Delete items from vector store
Query vector store
Once your vector store has been created and the relevant documents have been added you will most likely wish to query it during the running of your chain or agent.Query directly
Performing a simple similarity search can be done as follows:Filtering
MongoDB Atlas supports pre-filtering of results on other fields. They require you to define which metadata fields you plan to filter on by updating the index you created initially. Here’s an example:fields is the vector index, and the second item is the metadata property you want to filter on. The name of the property is the value of the path key. So the above index would allow us to search on a metadata field named source.
Then, in your code you can use MQL Query Operators for filtering.
The below example illustrates this:
Returning scores
If you want to execute a similarity search and receive the corresponding scores you can run:Query by turning into retriever
You can also transform the vector store into a retriever for easier usage in your chains.Usage for retrieval-augmented generation
For guides on how to use this vector store for retrieval-augmented generation (RAG), see the following sections:Closing connections
Make sure you close the client instance when you are finished to avoid excessive resource consumption:API reference
For detailed documentation of allMongoDBAtlasVectorSearch features and configurations head to the API reference.
Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.