The n8n MongoDB node finds, aggregates, inserts, updates and deletes documents, and each document it returns becomes one n8n item. The often-searched $items("MongoDB").length counts those items; the current, documented form is $("MongoDB").all().length. For large collections, page with a sorted range query instead of skip, and loop until a short page comes back.
The n8n MongoDB node connects a workflow to a MongoDB database and runs document operations on it, find, aggregate, insert, update, find and update, find and replace, and delete, with every returned document becoming one n8n item. Later nodes read those documents with expressions such as $("MongoDB").all(), the documented successor to the older $items("MongoDB") syntax that many workflows and forum answers still use.
Checked October 2026 against the n8n docs for the MongoDB node, MongoDB credentials, referencing previous nodes and the node output expression reference, and MongoDB's manual. Pipelines below are templates to adapt.
This guide is built around the pattern people actually search for: reading MongoDB results from another node, counting them, aggregating in the database instead of in n8n, and paging through collections too large to pull in one go. For other databases, see our n8n database automation guide and the n8n SQL Server guide; for ready-made workflows, the n8n templates library is the hub for this series.
- 01Trigger
Schedule Trigger for reports and syncs, Webhook for on-demand lookups.
- 02MongoDB: Aggregate
Filter, group and sort inside MongoDB so only the result reaches n8n.
- 03Guard empty results
Always Output Data plus an If node, so zero documents is handled on purpose.
- 04Use the documents
Later nodes read them with $("MongoDB").all(), .first() or .item.
- 05Page if needed
Loop back with the last _id until a short page returns.
- 06Write back
Update, insert, or send the result to another app.
Setting up the n8n MongoDB credential
The MongoDB credential offers two configuration types, per the n8n docs (checked October 2026):
- Connection String. Paste the driver connection string from MongoDB (in Atlas, Database, Connect, Drivers), replace the user and password placeholders, and enter the database name.
- Values. Enter host, database, user, password and port separately.
Both have a Use TLS option for servers configured with x.509 certificates, which asks for a CA certificate, public client certificate, private client key and passphrase. For Atlas, the n8n docs list one more prerequisite: a Project Owner must add the n8n IP addresses to the project's IP Access List. On n8n Cloud, those are the shared outbound addresses on the n8n IP address page, so keep the database user's password strong and its role narrow.
Create a database user for n8n with only the roles your workflows need. If an AI agent will use the MongoDB node as a tool, which n8n supports, give that agent a read-only user so a bad tool call cannot delete data.
What can the n8n MongoDB node do?
Document operations: aggregate documents, delete documents, find documents, find and replace, find and update, insert documents and update documents. Search Index operations: create, drop, list and update search indexes. n8n notes that every operation runs through the MongoDB Node driver, so query syntax follows MongoDB's own documentation.
Two things about how results flow trip people up. First, each document comes out as its own item, so a Find that returns 300 documents makes the next node run 300 times unless that node aggregates or is set to Execute Once. Second, a Find or Aggregate that returns nothing outputs no items at all, and the workflow quietly stops there. The node Settings tab has Always Output Data, which returns one empty item instead; n8n's node settings docs describe it.
What does the n8n expression $items("MongoDB") do?
$items("MongoDB") returns the output items of the node named MongoDB, and $items("MongoDB").length counts them, which for a Find or Aggregate is the number of documents returned. It is older n8n syntax: the current expression reference (checked October 2026) documents the $("<node-name>") methods instead and no longer lists $items(). If you inherit a workflow that uses it, rewrite it in the documented form so the next person can look it up:
| Older syntax | Documented form | Returns |
|---|---|---|
| $items("MongoDB") | $("MongoDB").all() | All output items of the node named MongoDB |
| $items("MongoDB").length | $("MongoDB").all().length | How many documents came back |
| $items("MongoDB")[0].json | $("MongoDB").first().json | The first document |
| $items() | $input.all() | All input items of the current node |
Per n8n's reference, all(), first() and last() take two optional arguments, branchIndex and runIndex, both defaulting to the first. That matters when the MongoDB node sits inside a loop and ran several times: $("MongoDB").all(0, 2) reads the third run. $("MongoDB").item returns the linked item, the document that produced the current item, which is usually what you want when each item downstream should see its own document. $("MongoDB").isExecuted tells you whether the node ran at all on this execution.
The node name is what links the expression to the node. Name MongoDB nodes after what they return ("Open orders", "Customer by email") rather than leaving the default, and expressions such as $("Open orders").all().length read like documentation.
How do you run a MongoDB aggregate in n8n?
The Aggregate documents operation takes a collection and a pipeline written as a JSON array of stages. It is the most useful MongoDB operation in n8n because it moves work into the database: instead of fetching thousands of documents and summarising them in a Code node, you ask MongoDB for the summary and receive a handful of items.
[
{ "$match": { "status": "paid", "$expr": { "$gte": ["$createdAt", { "$toDate": "{{ $now.minus({ days: 7 }).toISO() }}" }] } } },
{ "$group": { "_id": "$plan", "orders": { "$sum": 1 }, "revenue": { "$sum": "$amount" } } },
{ "$sort": { "revenue": -1 } }
]This example (illustrative field names) returns one item per plan with the count and total for the last seven days, ready for a Slack or email report. The pipeline is plain JSON, so dates and ObjectIds arrive as strings. Rather than depend on how they get converted on the way to the driver, the example converts inside the pipeline with MongoDB's own $toDate operator in an $expr; $toObjectId does the same for IDs. Test each stage in your MongoDB client before pasting it into n8n.
- Simple filters on one collection
- You want the documents themselves
- Small, predictable result sizes
- Quick lookups by email or ID
- Counts, sums, averages, top-N
- Joins with $lookup
- Reshaping documents before n8n sees them
- Paging with $match, $sort and $limit
Keep expressions inside pipelines to values you control, such as dates from $now or IDs from your own nodes. If a value comes from a webhook, validate its type first; a pipeline that drops raw outside input into a $match can be bent into a different query. Our n8n webhook guide covers authenticating senders before data gets that far.
Paging through large MongoDB collections in n8n
Pulling a whole large collection into one execution is slow and memory-hungry. MongoDB's documentation on skip() (checked October 2026) explains why the obvious fix is not the right one: skip scans from the beginning of the results before returning anything, so it gets slower as the offset grows, and range queries that use an index usually perform better.
- 1Set the starting point
An Edit Fields node sets lastId to the lowest possible ObjectId, 000000000000000000000000.
- 2MongoDB: Aggregate one page
A node named Page: match _id greater than lastId, sort by _id ascending, limit to your page size.
- 3Process the page
Write, transform or send the documents in this page.
- 4Carry the cursor forward
Set lastId to $("Page").last().json._id and the page count from .all().length.
- 5If: was the page full?
If the count equals the page size, loop back to the Aggregate node. Otherwise stop.
The page query, with an illustrative page size of 500 and the conversion done by MongoDB:
[
{ "$match": { "$expr": { "$gt": ["$_id", { "$toObjectId": "{{ $json.lastId }}" }] } } },
{ "$sort": { "_id": 1 } },
{ "$limit": 500 }
]Connecting a node's output back to an earlier node is how n8n's loop docs describe looping until a condition is met, with an If node deciding when to stop. Because each pass is a new run of the same MongoDB node, the run index matters: inside the loop, read the page you just fetched rather than the first run, and pass the run index explicitly if an expression returns the first page again. Paging on _id works on any collection because it is always indexed; to page in another order, sort on an indexed field and add _id as a tie-breaker.
For very long jobs, process pages in a sub-workflow called once per page, so each execution stays small and a failure only repeats one page. If you want to turn data workflows like these into a product with its own backend and users, our AI SaaS Builder program covers databases, auth, payments and automation end to end.
Writing documents back from n8n
Reads are half the job. The write operations map to familiar MongoDB patterns, and picking the right one avoids duplicates and lost updates:
- Insert documents for records that are new by definition, such as event logs or form submissions. Put a unique index on any natural key (an order ID, an email) so a retried execution fails loudly instead of inserting a second copy.
- Update documents for changing fields on documents you can identify by a key, such as setting a status after an email goes out.
- Find and update when you need the document back after changing it, for example claiming the next job from a queue collection in one step so two executions cannot claim the same job.
- Find and replace when the incoming record is the full, current version of the document and nothing else should survive.
- Delete documents sparingly, and preferably behind a filter you have tested with a Find first.
A pattern that works well for syncs from other tools: keep a field such as source_id with a unique index, look the record up by it, and branch with an If node into update or insert. It costs one extra read per record, but every branch is visible on the canvas, which makes the workflow easier for the next person to debug than one clever query. For bulk loads, reduce round trips by running the read once with an Aggregate that matches all incoming IDs, then compare the two lists with n8n's data nodes.
Common n8n MongoDB mistakes
- Relying on
$items()in new workflows. Use the documented$("<node>")methods. - Default node names. Three nodes called MongoDB, MongoDB1 and MongoDB2 make every expression ambiguous to a reader.
- Summarising in n8n what MongoDB could summarise. Push it into an Aggregate pipeline.
- Large skip values. Page with a range on an indexed field.
- No handling for zero results. Use Always Output Data and an If node.
- No failure alerting. Attach an error workflow; see our n8n error handling guide.
- Database user with the narrowest roles the workflow needs; read-only for agent tools
- n8n addresses added to the Atlas IP Access List
- MongoDB nodes renamed after what they return
- Expressions use $("Node").all(), .first(), .last() or .item, not $items()
- Summaries done in an Aggregate pipeline, not in a Code node
- Always Output Data on where zero results is a normal case
- Large reads paged by _id range with a loop and an If node
- Error workflow attached
n8n MongoDB FAQ
What does $items("MongoDB").length mean in n8n?
It counts how many items a node named MongoDB output, which for a Find or Aggregate operation is the number of documents returned. $items() is older n8n syntax and is not in the current expression reference, checked October 2026. The documented equivalent is $("MongoDB").all().length, where MongoDB is the exact name of the node on your canvas.
What operations does the n8n MongoDB node support?
For documents: aggregate, delete, find, find and replace, find and update, insert and update. For Atlas Search indexes: create, drop, list and update. The node runs every operation through the MongoDB Node driver, and it can also be attached to an AI agent as a tool. Checked October 2026 against the n8n docs.
How do I run a MongoDB aggregation in n8n?
Choose the Aggregate documents operation, pick the collection, and enter the pipeline as a JSON array of stages, such as $match, $group, $sort and $limit. Each document the pipeline returns becomes one n8n item. To return a single summary instead of many items, end the pipeline with a $group or $count stage.
Why does my workflow stop when MongoDB finds nothing?
When a Find or Aggregate returns no documents, the node outputs no items, so the nodes after it have nothing to run on. Turn on Always Output Data in the MongoDB node Settings tab and it returns one empty item instead. Then check for that case with an If node, because the empty item still counts as one item.
How do I paginate a large MongoDB collection in n8n?
Avoid growing skip values: MongoDB documents that skip scans from the beginning of the results, so it slows as the offset grows. Instead sort on an indexed field, fetch a page with $limit, remember the last value, and request the next page with $gt on that value. Loop back to the MongoDB node with an If node until a page comes back short.
How do I connect n8n to MongoDB Atlas?
Create a MongoDB credential in n8n with Connection String as the configuration type and paste the driver connection string from Atlas, replacing the user and password placeholders. Enter the database name. In Atlas, add the addresses n8n connects from to the project IP Access List; for n8n Cloud, the n8n docs publish its outbound IP list.
Building on your own data? Ship it as a product.
AI SaaS Builder, included in All Access, covers backends, databases, auth, payments and automation, with the other three programs, live coaching and the private community in one subscription.
Stuck on an expression?
Join the free Discord to ask questions and see what other builders are automating.