n8n MongoDB Database: NoSQL Query Aggregation Workflow
I use MongoDB with n8n because modern applications produce unstructured data that relational databases struggle to handle. Whether I’m ingesting API responses, storing event logs, or managing user profiles, MongoDB’s document model fits naturally. n8n connects to MongoDB through its dedicated node, giving me CRUD operations, aggregation pipelines, and indexing control from within my workflows.
MongoDB stores data as BSON documents — flexible JSON-like structures with dynamic schemas. This means I can evolve my data model without migrations. n8n’s MongoDB node handles the connection, authentication, and query execution. I’ve integrated it into data pipelines that process thousands of documents per minute.
Basic CRUD Operations
Create, read, update, and delete operations form the foundation. The n8n MongoDB node supports all four through its Operation parameter.
`javascript
// MongoDB node: insert a document
Operation: Insert
Collection: users
Document: {
“name”: “Jane Smith”,
“email”: “jane@example.com”,
“preferences”: { “theme”: “dark”, “notifications”: true },
“created_at”: {{new Date().toISOString()}}
}
// MongoDB node: find documents
Operation: Find
Collection: orders
Query: {
“status”: “pending”,
“amount”: { “$gte”: 100 }
}
Sort: { “created_at”: -1 }
Limit: 50
`
The Find operation returns an array of matching documents. I chain it with a Split In Batches node when processing large result sets — MongoDB drivers have cursor limits, and splitting batches prevents memory issues in n8n.
For updates, I use field-level modifications rather than replacing entire documents:
`javascript
// MongoDB node: update with modifiers
Operation: Update
Collection: inventory
Query: { “sku”: “SKU-12345” }
Update: {
“$set”: { “stock_level”: 150, “last_restocked”: {{new Date()}} },
“$inc”: { “total_sold”: 5 }
}
Upsert: true
`
The $inc operator atomically increments fields. Combined with $set, I can update multiple aspects of a document in a single operation. Upsert ensures the document creates if it doesn’t exist — useful for counter tracking and session storage.
Delete operations support both single and bulk removals:
`javascript
// MongoDB node: delete matching documents
Operation: Delete Many
Collection: temp_sessions
Query: { “expires_at”: { “$lt”: {{new Date().toISOString()}} } }
`
This cleanup pattern runs on a cron schedule, removing expired sessions and keeping the collection lean.
Aggregation Pipelines for Complex Queries
MongoDB’s aggregation framework transforms and analyzes data through a pipeline of stages. n8n’s MongoDB node passes the pipeline definition directly to the database, letting MongoDB do the heavy lifting.
Here’s a typical aggregation pipeline I use for sales reporting:
`javascript
// MongoDB node: aggregation pipeline
Operation: Aggregate
Collection: transactions
Pipeline: [
{
“$match”: {
“date”: { “$gte”: “2024-01-01”, “$lte”: “2024-12-31” },
“status”: “completed”
}
},
{
“$group”: {
“_id”: { “month”: { “$month”: “$date” }, “category”: “$category” },
“total_revenue”: { “$sum”: “$amount” },
“transaction_count”: { “$sum”: 1 },
“avg_order_value”: { “$avg”: “$amount” }
}
},
{
“$sort”: { “total_revenue”: -1 }
},
{
“$limit”: 20
}
]
`
The pipeline matches documents, groups by month and category, calculates aggregates, sorts by revenue, and limits results. MongoDB executes this entirely server-side — n8n receives only the final results. This is dramatically faster than fetching all transactions and processing them in a Code node.
For more complex transformations, I chain multiple aggregation stages:
`javascript
// Unwind arrays, lookup related data, project final shape
Pipeline: [
{ “$unwind”: “$items” },
{
“$lookup”: {
“from”: “products”,
“localField”: “items.product_id”,
“foreignField”: “_id”,
“as”: “product_details”
}
},
{ “$unwind”: “$product_details” },
{
“$addFields”: {
“line_total”: { “$multiply”: [“$items.quantity”, “$items.price”] },
“product_name”: “$product_details.name”
}
},
{
“$project”: {
“order_id”: 1,
“product_name”: 1,
“line_total”: 1,
“category”: “$product_details.category”
}
}
]
`
The $lookup stage performs a left outer join with the products collection. $unwind expands embedded arrays so each item becomes its own document. $addFields computes derived values. The result is a flattened dataset ready for reporting or export.
Indexing and Performance Optimization
MongoDB relies on indexes for query performance. Without proper indexes, aggregation pipelines scan entire collections. I create indexes through the MongoDB node’s Index operations:
`javascript
// MongoDB node: create compound index
Operation: Create Index
Collection: orders
Index: { “customer_id”: 1, “status”: 1, “created_at”: -1 }
Unique: false
`
Compound indexes support queries that filter on multiple fields. The sort order within the index matters — ascending or descending should match your most common query patterns.
For text search, I create a text index:
`javascript
// MongoDB node: create text index
Operation: Create Index
Collection: articles
Index: { “title”: “text”, “content”: “text” }
`
Then query with the aggregation $text stage:
`javascript
Pipeline: [
{
“$search”: {
“index”: “default”,
“text”: {
“query”: “automation workflow”,
“path”: [“title”, “content”]
}
}
},
{ “$sort”: { “score”: { “$meta”: “textScore” } } },
{ “$limit”: 10 }
]
`
I monitor query performance using the Explain feature. The MongoDB node’s Execute Command operation lets me run db.collection.explain("executionStats").find({...}) to analyze index usage and identify slow queries.
Connecting to Your Existing Setup
The n8n Docker Deployment guide covers running n8n with MongoDB as the backend database. Using MongoDB for both n8n’s internal storage and your workflow data simplifies infrastructure.
For connection strings and authentication, the n8n Docker Environment Variables reference explains how to configure database credentials securely in production.
The n8n Split In Batches node guide pairs perfectly with MongoDB aggregation results. Large aggregation outputs benefit from batch processing to avoid n8n memory limits.
Action Card: Quick MongoDB Setup
Test your MongoDB connection with this minimal workflow:
`javascript
// 1. MongoDB node: Insert One
// Collection: test_collection
// Document: { “message”: “Hello from n8n”, “timestamp”: {{new Date()}} }
// 2. MongoDB node: Find One
// Collection: test_collection
// Query: { “message”: “Hello from n8n” }
// 3. Response node: verify the document was inserted and retrieved
// 4. MongoDB node: Delete One
// Collection: test_collection
// Query: { “message”: “Hello from n8n” }
`
This four-step sequence confirms insert, read, and delete operations work. Replace the collection name and document structure for your actual use case.
