AI-Powered Movie Recommendation Agent with MongoDB
Overview
This workflow creates an intelligent AI agent that can answer movie-related queries by dynamically querying a MongoDB database using aggregation pipelines. It also allows users to save their favorite movies back into the database. The agent is powered by OpenAI's chat model and uses a webhook trigger to accept chat messages, making it ideal for building conversational interfaces for movie databases, recommendation systems, or any application that needs natural language access to MongoDB.
Nodes and Their Roles
-
When chat message received (Chat Trigger) — No auth. This node exposes a public webhook endpoint that accepts incoming chat messages. It is configured to allow all origins (
*). The workflow is triggered whenever a message is sent to the webhook URL. -
OpenAI Chat Model (LangChain Chat Model) — API Key auth. This node connects to OpenAI's chat completion API (e.g., GPT-4 or GPT-3.5). It requires an OpenAI API key stored in n8n credentials. The model processes the user's input and generates responses.
-
Window Buffer Memory (Memory Buffer Window) — No auth. This node maintains a short-term memory of the last 10 conversation turns. It helps the AI agent keep context across multiple messages.
-
MongoDBAggregate (MongoDB Tool) — MongoDB credentials (username/password or connection string). This node is a tool that executes MongoDB aggregation pipelines. It is configured with:
operation:aggregatecollection:moviesquery: A dynamic expression that uses$fromAIto let the AI generate the aggregation pipeline based on the user's request.toolDescription: Provides the AI with the document schema of themoviescollection (fields likeplot,genres,title,imdb.rating, etc.).
-
insertFavorite (Tool Workflow) — No auth (but the referenced sub-workflow may require its own credentials). This node calls another n8n workflow (
insertMongoDB) to insert a favorite movie into the database. It is configured with:name:insertFavoritesdescription: Instructs the AI to use this tool only when the user confirms a favorite movie, with the structure{"title": "received title"}.
-
AI Agent - Movie Recommendation (Agent) — No auth. This is the core agent node that orchestrates the conversation. It uses the OpenAI Chat Model, the Window Buffer Memory, and the two tools (MongoDBAggregate and insertFavorite). Its prompt instructs the AI to:
- Use
MongoDBAggregateto search for movies by providing a MongoDB aggregation pipeline. - Use
insertFavoriteonly when the user confirms a favorite movie. - The user's input is taken from
{{ $json.chatInput }}.
- Use
-
Sticky Note and Sticky Note1 — These are informational notes that describe the workflow's purpose and process. They do not affect execution.
Setup Instructions
- OpenAI API Key: Create an account at OpenAI and generate an API key. In n8n, add a new credential of type "OpenAI API" and paste your key.
- MongoDB Instance: You need a running MongoDB database (local or cloud, e.g., MongoDB Atlas). Create a database and a collection named
movieswith sample movie documents (the schema is described in the tool description). Add a MongoDB credential in n8n with your connection string or host/port/username/password. - Sub-workflow: Create a separate n8n workflow named
insertMongoDB(or update theworkflowIdin theinsertFavoritenode). This sub-workflow should accept an input with atitlefield and insert it into the MongoDBmoviescollection (or a separate favorites collection). - Webhook URL: After activating the workflow, n8n will provide a webhook URL. Use this URL to send chat messages (e.g., via a custom frontend, Postman, or a chat widget).
Use Cases and Variations
- Movie Recommendation Chatbot: Users can ask for movie recommendations based on genres, ratings, actors, or any field in the MongoDB documents. The AI generates appropriate aggregation pipelines on the fly.
- Personalized Favorites: Users can tell the AI to save a movie as a favorite, and the workflow inserts it into the database via the sub-workflow.
- Adapt to Other Collections: Modify the
MongoDBAggregatetool'scollectionandtoolDescriptionto work with any other MongoDB collection (e.g., products, books, restaurants). - Change AI Model: Replace the OpenAI Chat Model with another LangChain-supported model (e.g., Anthropic Claude, Google Gemini) by swapping the node and updating credentials.
- Add More Tools: Extend the agent with additional tools, such as a web search tool or a tool to update/delete documents.
- Authentication: For production, you may want to add authentication to the webhook (e.g., using a header auth or a custom credential) to prevent unauthorized access.
Workflow JSON
{
"id": "22PddLUgcjSJbT1w",
"meta": {
"instanceId": "fa7d5e2425ec76075df7100dbafffed91cc6f71f12fe92614bf78af63c54a61d",
"templateCredsSetupCompleted": true
},
"name": "MongoDB Agent",
"tags": [],
"nodes": [
{
"id": "d8c07efe-eca0-48cb-80e6-ea8117073c5f",
"name": "OpenAI Chat Model",
"type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
"position": [
1300,
560
],
"parameters": {
"options": {}
},
"credentials": {
"openAiApi": {
"id": "TreGPMKr9hrtCvVp",
"name": "OpenAi account"
}
},
"typeVersion": 1
},
{
"id": "636de178-7b68-429a-9371-41cf2a950076",
"name": "MongoDBAggregate",
"type": "n8n-nodes-base.mongoDbTool",
"position": [
1640,
540
],
"parameters": {
"query": "={{ $fromAI(\"pipeline\", \"The MongoDB pipeline to execute\" , \"string\" , [{\"$match\" : { \"rating\" : 5 } }])}}",
"operation": "aggregate",
"collection": "movies",
"descriptionType": "manual",
"toolDescription": "Get from AI the MongoDB Aggregation pipeline to get context based on the provided pipeline, the document structure of the documents is : {\n \"plot\": \"A group of bandits stage a brazen train hold-up, only to find a determined posse hot on their heels.\",\n \"genres\": [\n \"Short\",\n \"Western\"\n ],\n \"runtime\": 11,\n \"cast\": [\n \"A.C. Abadie\",\n \"Gilbert M. 'Broncho Billy' Anderson\",\n ...\n ],\n \"poster\": \"...jpg\",\n \"title\": \"The Great Train Robbery\",\n \"fullplot\": \"Among the earliest existing films in American cinema - notable as the ...\",\n \"languages\": [\n \"English\"\n ],\n \"released\": \"date\"\n },\n \"directors\": [\n \"Edwin S. Porter\"\n ],\n \"rated\": \"TV-G\",\n \"awards\": {\n \"wins\": 1,\n \"nominations\": 0,\n \"text\": \"1 win.\"\n },\n \"lastupdated\": \"2015-08-13 00:27:59.177000000\",\n \"year\": 1903,\n \"imdb\": {\n \"rating\": 7.4,"
},
"credentials": {
"mongoDb": {
"id": "8xGgiXzf2o0L4a0y",
"name": "MongoDB account"
}
},
"typeVersion": 1.1
// ... truncated (copy to see full JSON)How to Import This Workflow
- 1Copy the workflow JSON above using the Copy Workflow JSON button.
- 2Open your n8n instance and go to Workflows.
- 3Click Import from JSON and paste the copied workflow.
Don't have an n8n instance? Start your free trial at n8nautomation.cloud
Related Templates
Automated Blog Post Creation from News with AI and Blogger
This workflow automates the entire process of creating a fully SEO-optimized blog post from a news article. It fetches a trending technology news headline from Mediastack, generates relevant images from Pexels, uses two AI agents (via OpenRouter) to produce a title, slug, meta description, and a complete WordPress-compatible HTML blog post, then posts it directly to Blogger and sends you a Telegram notification. It's perfect for content marketers, bloggers, or anyone who wants to consistently publish fresh, data-driven content without manual effort. Node Breakdown Schedule Trigger (No auth) — Runs the workflow at a set interval (configured every minute by default, but you should change it to daily or hourly). Mediastack News (API Key auth via query parameter) — Fetches the latest technology news article in English from the Mediastack API. Parameters: set to . Genarate image (API Key auth via header, ) — Searches Pexels for up to 2 images related to the news title. Parameters: = , = 2. Send a text message1 (Telegram bot token auth) — Sends a Telegram message with the generated image URLs to the chat ID stored in . AI Agent (Uses OpenRouter Chat Model — API Key auth) — This agent takes the news title and returns a JSON object with three fields: , , and (meta description). The prompt includes strict guidelines for SEO-friendly output. OpenRouter Chat Model (API Key auth) — The language model for the first AI agent, using . Parsing (No auth) — A Code node that cleans the raw AI output (removes markdown code fences) and parses the JSON into usable fields. Copywriter AI Agent (Uses OpenRouter Chat Model2 — API Key auth) — This agent writes a complete 1,000-word SEO blog post in HTML format. It uses the title, meta, and the two images from Pexels. The prompt is very detailed, specifying structure, keyword placement, and styling. OpenRouter Chat Model2 (API Key auth) — Same model as the first, but used for the second agent. Cleanup HTML (No auth) — A Set node that removes any leftover htmlurlhttps://www.googleapis.com/blogger/v3/blogs/$vars.bloggerid/postsPOSThttpQueryAuthAuthorization$vars.telegramchatid$vars.bloggeridbusinesssports`) to match your niche. Multi-language Support — Modify the Mediastack query to fetch news in other languages, and adjust the AI prompts to write in that language. Custom Image Sources — Replace the Pexels node with another image API (e.g., Unsplash) or use a local image generation model. Different CMS — Swap the Blogger HTTP Request node with WordPress or any other CMS API (just change the URL and body format). Human-in-the-Loop — Add a Slack or email approval step before publishing to review the AI-generated content. Newsletter Integration — Instead of posting to a blog, send the formatted content as an email newsletter via Gmail or SendGrid.
AI Chat Agent with OpenAI, Memory, and Web Search
Overview This workflow creates an intelligent AI chat agent that combines OpenAI's language model with conversational memory and real-time web search capabilities via SerpAPI. It is designed to power interactive chat applications where the AI can remember context across messages and fetch up-to-date information from the internet when needed. This is particularly useful for building customer support bots, research assistants, or any conversational interface that requires both knowledge retention and live data access. The workflow is triggered by incoming chat messages and processes them through an AI agent that coordinates between the language model, memory buffer, and search tool. The agent can decide when to use web search to answer questions that require current information, while maintaining conversation history for coherent multi-turn dialogues. Workflow Steps Manual Trigger (No auth) — This node allows you to manually start the workflow for testing purposes. It has no parameters configured and simply provides a button to execute the workflow on demand. When chat message received (No auth) — This is a webhook-based trigger that listens for incoming chat messages. It generates a unique webhook URL that you can integrate with your chat frontend or messaging platform. The parameter is empty, meaning default webhook behavior is used. AI Agent (No auth) — This is the core orchestrator node that manages the conversation flow. It coordinates between the OpenAI model, memory buffer, and SerpAPI tool. The agent decides which tool to use based on the user's query and maintains the conversation state. OpenAI Chat Model (API Key auth) — This node connects to OpenAI's GPT-4o-mini model to generate responses. It requires an OpenAI API key configured in n8n credentials. The parameter is set to , which is a cost-effective and fast model suitable for chat applications. The parameter is empty, using default model settings. Window Buffer Memory (No auth) — This node implements a sliding window memory that stores recent conversation history. It allows the AI to remember context from previous messages within a configurable window size. The parameters are empty, using default memory settings. SerpAPI (API Key auth) — This tool node enables web search functionality via SerpAPI (Google Search API). It requires a SerpAPI API key configured in n8n credentials. The parameter is empty, using default search settings. The agent calls this node when it determines that real-time web data is needed to answer a query. Setup Instructions To use this workflow, you need the following accounts and credentials: OpenAI Account: Sign up at platform.openai.com and create an API key. In n8n, create an "OpenAI" credential and paste your API key. SerpAPI Account: Register at serpapi.com and obtain an API key. In n8n, create a "SerpAPI" credential with your key. Webhook URL: After activating the workflow, copy the webhook URL from the "When chat message received" node. Integrate this URL into your chat application (e.g., a custom web chat widget, Slack app, or Telegram bot). Optional: Configure the memory window size in the "Window Buffer Memory" node if you want to limit or extend conversation context. Use Cases and Variations This workflow can be adapted for multiple scenarios: Customer Support Bot: Replace SerpAPI with a knowledge base tool (e.g., vector store or database lookup) to answer product-specific questions. Research Assistant: Keep SerpAPI for web search and add additional tools like Wikipedia or news APIs. Multi-Platform Chat: Connect the webhook to different messaging platforms (Slack, Discord, Telegram) by adding appropriate trigger nodes. Personal Assistant: Add calendar or email tools to let the AI manage schedules and send messages. Language Translation: Replace the OpenAI model with a translation-specific model or add a translation tool node. To extend the workflow, you can add more tool nodes (e.g., database queries, file operations) and connect them to the AI Agent. The agent will automatically learn to use new tools based on their descriptions.
AI Social Media Content Generator using Local Ollama
This workflow uses a local Ollama instance to automatically generate platform-specific social media content (Twitter, LinkedIn, Reddit, Instagram) for a given topic, brand voice, and target audience. It then reviews and polishes the content for consistency and quality. Perfect for content creators, marketers, or developers who want to quickly produce multi-platform posts with full control over AI model and data privacy. Workflow Steps Manual Trigger (No auth) — Manually start the workflow to generate content on demand. Content Parameters — A Set node that defines three input variables: , , and . These can be edited directly in the node to customize each generation. Generate All Platform Content (Ollama) — An HTTP Request node (No auth) that sends a prompt to the local Ollama API (). It requests the model () to output structured JSON containing posts for Twitter, LinkedIn, Reddit, and Instagram. Parse Content JSON — A Code node that extracts and parses the JSON response from Ollama, merging it with the original topic and a timestamp. Review & Polish (Ollama) — A second HTTP Request node (No auth) that sends the generated content to Ollama for quality review (grammar, tone, formatting) and returns corrected versions if needed. Final Content Output — A Code node that merges the reviewed output with the original and flags whether the content was reviewed. Setup Instructions Ollama: Download and install Ollama on your local machine. Pull the model by running . Ensure Ollama is running (default on ). n8n: The workflow uses only local connections—no external API keys or accounts required. Simply import the JSON into your n8n instance and execute it manually. Customization: Modify the node to change the topic, brand voice, or target audience. Adjust the prompt in the first HTTP Request node to add or remove platforms. Use Cases & Variations Scheduled content generation: Replace the Manual Trigger with a Cron trigger to generate posts daily or weekly. Multi-model support: Change the parameter in Ollama calls to use other models like , , or . Platform expansion: Edit the prompt to include additional platforms (e.g., Facebook, TikTok) or output formats. Integration with publishing tools: After the final output, add nodes to post directly to Twitter via API, save to a Google Sheet, or send to a CMS. Language/tonality: Adjust the and prompt instructions to generate content in different languages or styles.