!function(){function t(t){document.documentElement.setAttribute("data-theme",t)}var e=function(){var t=null;try{t=new URLSearchParams(window.location.search).get("docusaurus-theme")}catch(t){}return t}()||function(){var t=null;try{t=localStorage.getItem("theme")}catch(t){}return t}();t(null!==e?e:"light")}(),document.documentElement.setAttribute("data-announcement-bar-initially-dismissed",function(){try{return"true"===localStorage.getItem("docusaurus.announcement.dismiss")}catch(t){}return!1}())

[Skip to main content](#__docusaurus_skipToContent_fallback)

You are viewing the **preview** v0.2 docs. View the **stable** v0.1 docs [here](/v0.1/docs/get_started/introduction/). Leave feedback on the v0.2 docs [here](https://github.com/langchain-ai/langchainjs/discussions/5386).

[

![🦜️🔗 Langchain](/v0.2/img/brand/wordmark.png)![🦜️🔗 Langchain](/v0.2/img/brand/wordmark-dark.png)

](/v0.2/)[Integrations](/v0.2/docs/integrations/platforms/)[API Reference](https://v02.api.js.langchain.com)

[More](#)

*   [People](/v0.2/docs/people/)
*   [Community](/v0.2/docs/community)
*   [Tutorials](/v0.2/docs/additional_resources/tutorials)
*   [Contributing](/v0.2/docs/contributing)

[v0.2](#)

*   [v0.2](/v0.2/docs/introduction)
*   [v0.1](https://js.langchain.com/v0.1/docs/get_started/introduction)

[🦜🔗](#)

*   [LangSmith](https://smith.langchain.com)
*   [LangSmith Docs](https://docs.smith.langchain.com)
*   [LangChain Hub](https://smith.langchain.com/hub)
*   [LangServe](https://github.com/langchain-ai/langserve)
*   [Python Docs](https://python.langchain.com/)

[Chat](https://chatjs.langchain.com)[](https://github.com/langchain-ai/langchainjs)

Search

*   [Providers](/v0.2/docs/integrations/platforms/)
    
    *   [Providers](/v0.2/docs/integrations/platforms/)
    *   [Anthropic](/v0.2/docs/integrations/platforms/anthropic)
    *   [AWS](/v0.2/docs/integrations/platforms/aws)
    *   [Google](/v0.2/docs/integrations/platforms/google)
    *   [Microsoft](/v0.2/docs/integrations/platforms/microsoft)
    *   [OpenAI](/v0.2/docs/integrations/platforms/openai)
*   [Components](/v0.2/docs/integrations/components)
    
    *   [Chat models](/v0.2/docs/integrations/chat/)
        
    *   [LLMs](/v0.2/docs/integrations/llms/)
        
    *   [Embedding models](/v0.2/docs/integrations/text_embedding)
        
    *   [Document loaders](/v0.2/docs/integrations/document_loaders)
        
    *   [Document transformers](/v0.2/docs/integrations/document_transformers)
        
    *   [Vector stores](/v0.2/docs/integrations/vectorstores)
        
        *   [Memory](/v0.2/docs/integrations/vectorstores/memory)
        *   [AnalyticDB](/v0.2/docs/integrations/vectorstores/analyticdb)
        *   [Astra DB](/v0.2/docs/integrations/vectorstores/astradb)
        *   [Azure AI Search](/v0.2/docs/integrations/vectorstores/azure_aisearch)
        *   [Azure Cosmos DB](/v0.2/docs/integrations/vectorstores/azure_cosmosdb)
        *   [Cassandra](/v0.2/docs/integrations/vectorstores/cassandra)
        *   [Chroma](/v0.2/docs/integrations/vectorstores/chroma)
        *   [ClickHouse](/v0.2/docs/integrations/vectorstores/clickhouse)
        *   [CloseVector](/v0.2/docs/integrations/vectorstores/closevector)
        *   [Cloudflare Vectorize](/v0.2/docs/integrations/vectorstores/cloudflare_vectorize)
        *   [Convex](/v0.2/docs/integrations/vectorstores/convex)
        *   [Couchbase](/v0.2/docs/integrations/vectorstores/couchbase)
        *   [Elasticsearch](/v0.2/docs/integrations/vectorstores/elasticsearch)
        *   [Faiss](/v0.2/docs/integrations/vectorstores/faiss)
        *   [Google Vertex AI Matching Engine](/v0.2/docs/integrations/vectorstores/googlevertexai)
        *   [SAP HANA Cloud Vector Engine](/v0.2/docs/integrations/vectorstores/hanavector)
        *   [HNSWLib](/v0.2/docs/integrations/vectorstores/hnswlib)
        *   [LanceDB](/v0.2/docs/integrations/vectorstores/lancedb)
        *   [Milvus](/v0.2/docs/integrations/vectorstores/milvus)
        *   [Momento Vector Index (MVI)](/v0.2/docs/integrations/vectorstores/momento_vector_index)
        *   [MongoDB Atlas](/v0.2/docs/integrations/vectorstores/mongodb_atlas)
        *   [MyScale](/v0.2/docs/integrations/vectorstores/myscale)
        *   [Neo4j Vector Index](/v0.2/docs/integrations/vectorstores/neo4jvector)
        *   [Neon Postgres](/v0.2/docs/integrations/vectorstores/neon)
        *   [OpenSearch](/v0.2/docs/integrations/vectorstores/opensearch)
        *   [PGVector](/v0.2/docs/integrations/vectorstores/pgvector)
        *   [Pinecone](/v0.2/docs/integrations/vectorstores/pinecone)
        *   [Prisma](/v0.2/docs/integrations/vectorstores/prisma)
        *   [Qdrant](/v0.2/docs/integrations/vectorstores/qdrant)
        *   [Redis](/v0.2/docs/integrations/vectorstores/redis)
        *   [Rockset](/v0.2/docs/integrations/vectorstores/rockset)
        *   [SingleStore](/v0.2/docs/integrations/vectorstores/singlestore)
        *   [Supabase](/v0.2/docs/integrations/vectorstores/supabase)
        *   [Tigris](/v0.2/docs/integrations/vectorstores/tigris)
        *   [Turbopuffer](/v0.2/docs/integrations/vectorstores/turbopuffer)
        *   [TypeORM](/v0.2/docs/integrations/vectorstores/typeorm)
        *   [Typesense](/v0.2/docs/integrations/vectorstores/typesense)
        *   [Upstash Vector](/v0.2/docs/integrations/vectorstores/upstash)
        *   [USearch](/v0.2/docs/integrations/vectorstores/usearch)
        *   [Vectara](/v0.2/docs/integrations/vectorstores/vectara)
        *   [Vercel Postgres](/v0.2/docs/integrations/vectorstores/vercel_postgres)
        *   [Voy](/v0.2/docs/integrations/vectorstores/voy)
        *   [Weaviate](/v0.2/docs/integrations/vectorstores/weaviate)
        *   [Xata](/v0.2/docs/integrations/vectorstores/xata)
        *   [Zep](/v0.2/docs/integrations/vectorstores/zep)
    *   [Retrievers](/v0.2/docs/integrations/retrievers)
        
    *   [Tools](/v0.2/docs/integrations/tools)
        
    *   [Toolkits](/v0.2/docs/integrations/toolkits)
        
    *   [Stores](/v0.2/docs/integrations/stores/)
        

*   [](/v0.2/)
*   [Components](/v0.2/docs/integrations/components)
*   [Vector stores](/v0.2/docs/integrations/vectorstores)
*   MongoDB Atlas

On this page

MongoDB Atlas
=============

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](https://nextjs.org/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes).

LangChain.js supports MongoDB Atlas as a vector store, and supports both standard similarity search and maximal marginal relevance search, which takes a combination of documents are most similar to the inputs, then reranks and optimizes for diversity.

Setup[​](#setup "Direct link to Setup")
---------------------------------------

### Installation[​](#installation "Direct link to Installation")

First, add the Node MongoDB SDK to your project:

*   npm
*   Yarn
*   pnpm

    npm install -S mongodb

    yarn add mongodb

    pnpm add mongodb

### Initial Cluster Configuration[​](#initial-cluster-configuration "Direct link to Initial Cluster Configuration")

Next, you'll need create a MongoDB Atlas cluster. Navigate to the [MongoDB Atlas website](https://www.mongodb.com/atlas/database) and create an account if you don't already have one.

Create and name a cluster when prompted, then find it under `Database`. Select `Collections` and create either a blank collection or one from the provided sample data.

**Note** The cluster created must be MongoDB 7.0 or higher. If you are using a pre-7.0 version of MongoDB, you must use a version of langchainjs<=0.0.163.

### Creating an Index[​](#creating-an-index "Direct link to Creating an Index")

After configuring your cluster, you'll need to create an index on the collection field you want to search over.

Switch to the `Atlas Search` tab and click `Create Search Index`. From there, make sure you select `Atlas Vector Search - JSON Editor`, then select the appropriate database and collection and paste the following into the textbox:

    {  "fields": [    {      "numDimensions": 1024,      "path": "embedding",      "similarity": "euclidean",      "type": "vector"    }  ]}

Note that the `dimensions` property should match the dimensionality of the embeddings you are using. For example, Cohere embeddings have 1024 dimensions, and by default OpenAI embeddings have 1536:

**Note:** By default the vector store expects an index name of `default`, an indexed collection field name of `embedding`, and a raw text field name of `text`. You should initialize the vector store with field names matching your index name collection schema as shown below.

Finally, proceed to build the index.

Usage[​](#usage "Direct link to Usage")
---------------------------------------

tip

See [this section for general instructions on installing integration packages](/v0.2/docs/how_to/installation#installing-integration-packages).

*   npm
*   Yarn
*   pnpm

    npm install @langchain/community

    yarn add @langchain/community

    pnpm add @langchain/community

### Ingestion[​](#ingestion "Direct link to Ingestion")

    import { MongoDBAtlasVectorSearch } from "@langchain/mongodb";import { CohereEmbeddings } from "@langchain/cohere";import { MongoClient } from "mongodb";const client = new MongoClient(process.env.MONGODB_ATLAS_URI || "");const namespace = "langchain.test";const [dbName, collectionName] = namespace.split(".");const collection = client.db(dbName).collection(collectionName);const vectorstore = await MongoDBAtlasVectorSearch.fromTexts(  ["Hello world", "Bye bye", "What's this?"],  [{ id: 2 }, { id: 1 }, { id: 3 }],  new CohereEmbeddings(),  {    collection,    indexName: "default", // The name of the Atlas search index. Defaults to "default"    textKey: "text", // The name of the collection field containing the raw content. Defaults to "text"    embeddingKey: "embedding", // The name of the collection field containing the embedded text. Defaults to "embedding"  });const assignedIds = await vectorstore.addDocuments([  { pageContent: "upsertable", metadata: {} },]);const upsertedDocs = [{ pageContent: "overwritten", metadata: {} }];await vectorstore.addDocuments(upsertedDocs, { ids: assignedIds });await client.close();

#### API Reference:

*   [MongoDBAtlasVectorSearch](https://v02.api.js.langchain.com/classes/langchain_mongodb.MongoDBAtlasVectorSearch.html) from `@langchain/mongodb`
*   [CohereEmbeddings](https://v02.api.js.langchain.com/classes/langchain_cohere.CohereEmbeddings.html) from `@langchain/cohere`

### Search[​](#search "Direct link to Search")

    import { MongoDBAtlasVectorSearch } from "@langchain/mongodb";import { CohereEmbeddings } from "@langchain/cohere";import { MongoClient } from "mongodb";const client = new MongoClient(process.env.MONGODB_ATLAS_URI || "");const namespace = "langchain.test";const [dbName, collectionName] = namespace.split(".");const collection = client.db(dbName).collection(collectionName);const vectorStore = new MongoDBAtlasVectorSearch(new CohereEmbeddings(), {  collection,  indexName: "default", // The name of the Atlas search index. Defaults to "default"  textKey: "text", // The name of the collection field containing the raw content. Defaults to "text"  embeddingKey: "embedding", // The name of the collection field containing the embedded text. Defaults to "embedding"});const resultOne = await vectorStore.similaritySearch("Hello world", 1);console.log(resultOne);await client.close();

#### API Reference:

*   [MongoDBAtlasVectorSearch](https://v02.api.js.langchain.com/classes/langchain_mongodb.MongoDBAtlasVectorSearch.html) from `@langchain/mongodb`
*   [CohereEmbeddings](https://v02.api.js.langchain.com/classes/langchain_cohere.CohereEmbeddings.html) from `@langchain/cohere`

### Maximal marginal relevance[​](#maximal-marginal-relevance "Direct link to Maximal marginal relevance")

    import { MongoDBAtlasVectorSearch } from "@langchain/mongodb";import { CohereEmbeddings } from "@langchain/cohere";import { MongoClient } from "mongodb";const client = new MongoClient(process.env.MONGODB_ATLAS_URI || "");const namespace = "langchain.test";const [dbName, collectionName] = namespace.split(".");const collection = client.db(dbName).collection(collectionName);const vectorStore = new MongoDBAtlasVectorSearch(new CohereEmbeddings(), {  collection,  indexName: "default", // The name of the Atlas search index. Defaults to "default"  textKey: "text", // The name of the collection field containing the raw content. Defaults to "text"  embeddingKey: "embedding", // The name of the collection field containing the embedded text. Defaults to "embedding"});const resultOne = await vectorStore.maxMarginalRelevanceSearch("Hello world", {  k: 4,  fetchK: 20, // The number of documents to return on initial fetch});console.log(resultOne);// Using MMR in a vector store retrieverconst retriever = await vectorStore.asRetriever({  searchType: "mmr",  searchKwargs: {    fetchK: 20,    lambda: 0.1,  },});const retrieverOutput = await retriever.invoke("Hello world");console.log(retrieverOutput);await client.close();

#### API Reference:

*   [MongoDBAtlasVectorSearch](https://v02.api.js.langchain.com/classes/langchain_mongodb.MongoDBAtlasVectorSearch.html) from `@langchain/mongodb`
*   [CohereEmbeddings](https://v02.api.js.langchain.com/classes/langchain_cohere.CohereEmbeddings.html) from `@langchain/cohere`

### Metadata filtering[​](#metadata-filtering "Direct link to Metadata 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. Here's an example:

    {  "fields": [    {      "numDimensions": 1024,      "path": "embedding",      "similarity": "euclidean",      "type": "vector"    },    {      "path": "docstore_document_id",      "type": "filter"    }  ]}

Above, the first item in `fields` is the vector index, and the second item is the metadata property you want to filter on. The name of the property is `path`, so the above index would allow us to search on a metadata field named `docstore_document_id`.

Then, in your code you can use [MQL Query Operators](https://www.mongodb.com/docs/manual/reference/operator/query/) for filtering. Here's an example:

    import { MongoDBAtlasVectorSearch } from "@langchain/mongodb";import { CohereEmbeddings } from "@langchain/cohere";import { MongoClient } from "mongodb";import { sleep } from "langchain/util/time";const client = new MongoClient(process.env.MONGODB_ATLAS_URI || "");const namespace = "langchain.test";const [dbName, collectionName] = namespace.split(".");const collection = client.db(dbName).collection(collectionName);const vectorStore = new MongoDBAtlasVectorSearch(new CohereEmbeddings(), {  collection,  indexName: "default", // The name of the Atlas search index. Defaults to "default"  textKey: "text", // The name of the collection field containing the raw content. Defaults to "text"  embeddingKey: "embedding", // The name of the collection field containing the embedded text. Defaults to "embedding"});await vectorStore.addDocuments([  {    pageContent: "Hey hey hey",    metadata: { docstore_document_id: "somevalue" },  },]);const retriever = vectorStore.asRetriever({  filter: {    preFilter: {      docstore_document_id: {        $eq: "somevalue",      },    },  },});// Mongo has a slight processing delay between ingest and availabilityawait sleep(2000);const results = await retriever.invoke("goodbye");console.log(results);await client.close();

#### API Reference:

*   [MongoDBAtlasVectorSearch](https://v02.api.js.langchain.com/classes/langchain_mongodb.MongoDBAtlasVectorSearch.html) from `@langchain/mongodb`
*   [CohereEmbeddings](https://v02.api.js.langchain.com/classes/langchain_cohere.CohereEmbeddings.html) from `@langchain/cohere`
*   [sleep](https://v02.api.js.langchain.com/functions/langchain_util_time.sleep.html) from `langchain/util/time`

* * *

#### Was this page helpful?

  

#### You can leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchainjs/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E).

[

Previous

Momento Vector Index (MVI)

](/v0.2/docs/integrations/vectorstores/momento_vector_index)[

Next

MyScale

](/v0.2/docs/integrations/vectorstores/myscale)

*   [Setup](#setup)
    *   [Installation](#installation)
    *   [Initial Cluster Configuration](#initial-cluster-configuration)
    *   [Creating an Index](#creating-an-index)
*   [Usage](#usage)
    *   [Ingestion](#ingestion)
    *   [Search](#search)
    *   [Maximal marginal relevance](#maximal-marginal-relevance)
    *   [Metadata filtering](#metadata-filtering)

Community

*   [Discord](https://discord.gg/cU2adEyC7w)
*   [Twitter](https://twitter.com/LangChainAI)

GitHub

*   [Python](https://github.com/langchain-ai/langchain)
*   [JS/TS](https://github.com/langchain-ai/langchainjs)

More

*   [Homepage](https://langchain.com)
*   [Blog](https://blog.langchain.dev)

Copyright © 2024 LangChain, Inc.