For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.

Query MongoDB with Natural Language Using LangChain and LangGraph

You can use the LangChain MongoDB integration to run natural language MongoDB queries. In this tutorial, you build a basic AI agent that converts natural language to MQL by using the ReAct Agent framework and the MongoDB Agent Toolkit.

  • Have a MongoDB cluster and user.

  • Add the Restaurants sample dataset to your MongoDB cluster.

  • Have an OpenAI API key.

  • Run the following to install required dependencies:

    pip install langchain-mongodb langchain-openai langgraph

This agent leverages a predefined set of tools with which it executes a step-by-step plan defined by a LLM. When a user submits a prompt to the agent, the agent sends a request to the LLM that details its available tools and the user's desired outcome. With that information, the LLM generates a specific series of steps that leverage the agent's available toolset to achieve the user's desired outcome.

The agent then executes the steps and confirms success, or executes updated steps as needed, by sending intermediate results back to the LLM for analysis. And finally, the system's results are returned to the user.

1

In your terminal, populate and run the following command to set the required environment variable.

export OPENAI_API_KEY=<your-openai-api-key>
2

Copy and paste the following into a local file called natural_language_to_mql.py.

Key Points

  • self.toolkit, the tools that the agent can use, is an instance of the MongoDB Toolkit.

  • self.agent, the agent itself, is an instance of the ReAct Agent framework, which takes self.toolkit as a parameter.

import osfrom langchain_openai import ChatOpenAIfrom langgraph.prebuilt import create_react_agentfrom langchain_mongodb.agent_toolkit import ( MONGODB_AGENT_SYSTEM_PROMPT, MongoDBDatabase, MongoDBDatabaseToolkit,) MONGODB_URI = '<connection-string>'DB_NAME = 'sample_restaurants'NATURAL_LANGUAGE_QUERY = 'Find all restaurants that serve hamburgers.' class NaturalLanguageToMQL: def __init__(self): self.llm = ChatOpenAI(model="gpt-4o-mini", timeout=60) self.system_message = MONGODB_AGENT_SYSTEM_PROMPT.format(top_k=5) self.db_wrapper = MongoDBDatabase.from_connection_string( MONGODB_URI, database=DB_NAME) self.toolkit = MongoDBDatabaseToolkit(db=self.db_wrapper, llm=self.llm) self.agent = create_react_agent( self.llm, self.toolkit.get_tools(), state_modifier=self.system_message) self.messages = [] def convert_to_mql_and_execute_query(self, query): # Start the agent with the agent.stream() method events = self.agent.stream( {"messages": [("user", query)]}, stream_mode="values", ) # Add output (events) from the agent to the self.messages list for event in events: self.messages.extend(event["messages"]) def print_results(self): # Print the the end-user's expected output from # the final message produced by the agent. print(self.messages[-1].content) def main(): converter = NaturalLanguageToMQL() converter.convert_to_mql_and_execute_query(NATURAL_LANGUAGE_QUERY) converter.print_results() if __name__ == '__main__': main()
3

Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.

Your connection string should use the following format:

mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net

IMPORTANT: Ensure that your connection string includes your database user's credentials. To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.

From the directory in which you saved the local file, run the following command. Your results might vary.

python natural_language_to_mql.py
Here are some restaurants that serve hamburgers: 1. **Wendy's** - Address: 469 Flatbush Avenue, Brooklyn, NY 11225 - Borough: Brooklyn 2. **White Castle** - Address: 531 Myrtle Avenue, Brooklyn, NY 11205 - Borough: Brooklyn 3. **McDonald's** - Address: 75-50 101 Avenue, Queens, NY 11416 - Borough: Queens 4. **McDonald's** - Address: 943 Flatbush Avenue, Brooklyn, NY 11226 - Borough: Brooklyn 5. **McDonald's** - Address: 395 Flatbush Avenue Extension, Brooklyn, NY 11201 - Borough: Brooklyn Let me know if you'd like more details or additional results!