DEV Community

Pirate Prentice
Pirate Prentice

Posted on

n8n MongoDB Node: Query, Insert, Update, and Delete Documents (Free Workflow JSON)

n8n MongoDB Node: Query, Insert, Update, and Delete Documents (Free Workflow JSON)

If you store data in MongoDB and want to automate what happens with it, the n8n MongoDB node is your bridge. You can read documents, insert new ones, update existing records, and delete entries — all without writing a backend service.

This guide covers every operation the MongoDB node supports, common credential gotchas, and a free copy-paste workflow JSON at the end.


What the n8n MongoDB Node Does

The MongoDB node connects directly to your MongoDB instance (Atlas, self-hosted, or Docker) via the MongoDB driver. It supports:

Operation What it does
Find Query documents with a filter
Insert Insert one or many documents
Update Update matching documents
Delete Remove matching documents
Aggregate Run an aggregation pipeline

All operations run over a direct connection — no REST API middleware required.


Setting Up MongoDB Credentials in n8n

In n8n, go to Credentials → New → MongoDB.

You need:

  • Connection String (recommended): paste your full MongoDB URI, e.g.:
  mongodb+srv://username:password@cluster.mongodb.net/myDatabase?retryWrites=true&w=majority
Enter fullscreen mode Exit fullscreen mode
  • Database: the name of the database to operate on

Common credential gotchas

Atlas: whitelist your n8n IP. MongoDB Atlas blocks all IPs by default. In Atlas → Network Access, add your n8n server's public IP (or 0.0.0.0/0 for development — tighten this in production).

URL-encode special characters in passwords. If your password contains @, #, /, or %, encode them (@%40, etc.) or the connection string will parse incorrectly.

Self-hosted MongoDB: enable remote connections. By default MongoDB binds to 127.0.0.1. Set bindIp: 0.0.0.0 in mongod.conf and open port 27017 in your firewall.

TLS/SSL on Atlas is required. The +srv URI scheme handles this automatically. If you're using a plain mongodb:// URI to Atlas, add ?tls=true.


Operation 1: Find Documents

Use Find to query documents matching a filter.

Node settings:

  • Operation: Find
  • Collection: leads (your collection name)
  • Query: { "status": "new" }
  • Limit: 50 (optional; avoids pulling thousands of docs)
  • Sort: { "createdAt": -1 } (newest first, optional)

Output: Each matching document becomes an n8n item. Fields are available as {{ $json.fieldName }}.

Find with a dynamic filter

You can reference upstream data in the query using n8n expressions:

{ "email": "{{ $json.email }}" }
Enter fullscreen mode Exit fullscreen mode

This lets you look up a specific document based on a webhook payload, form submission, or previous node output.

Find with projection (return specific fields only)

Use the Projection field to limit returned fields:

{ "email": 1, "name": 1, "_id": 0 }
Enter fullscreen mode Exit fullscreen mode

1 = include, 0 = exclude. _id is included by default unless you explicitly exclude it.


Operation 2: Insert Documents

Use Insert to add one or more documents to a collection.

Node settings:

  • Operation: Insert
  • Collection: leads
  • Fields: map your upstream data to document fields

Inserting a single document:
Set the fields directly. The MongoDB node maps each key-value pair into the document.

Inserting multiple documents:
If your upstream node returns multiple items (e.g., a batch from a CSV or webhook array), the MongoDB node will insert one document per n8n item when run in normal mode. Use Split In Batches upstream if you need to control throughput.

Auto-generated _id

MongoDB auto-generates an _id (ObjectId) if you don't supply one. The inserted document's _id is returned in the output as $json._id, which you can pass downstream (e.g., to send a confirmation email with the record ID).


Operation 3: Update Documents

Use Update to modify existing documents.

Node settings:

  • Operation: Update
  • Collection: leads
  • Query: { "email": "{{ $json.email }}" } — which document(s) to update
  • Update: the update operator expression

Update operators

MongoDB updates use operators, not plain field assignments:

{ "$set": { "status": "contacted", "updatedAt": "{{ $now }}" } }
Enter fullscreen mode Exit fullscreen mode

Common operators:

Operator Effect
$set Set field values
$unset Remove a field
$inc Increment a numeric field
$push Append to an array field
$pull Remove from an array field

Mistake to avoid: Using { "status": "contacted" } without $set will replace the entire document with just { "status": "contacted" }. Always wrap field changes in $set.

Upsert (insert if not found)

Enable the Upsert toggle in the node. If no document matches the query, MongoDB will insert a new one with the update expression applied. Useful for sync workflows where you want to create-or-update without checking first.


Operation 4: Delete Documents

Use Delete to remove matching documents.

Node settings:

  • Operation: Delete
  • Collection: leads
  • Query: { "status": "unsubscribed" }

Warning: Without a query filter, Delete will remove ALL documents in the collection. Always double-check your filter before running delete operations on production data.

The node returns a count of deleted documents in $json.deletedCount.


Operation 5: Aggregate

Use Aggregate to run MongoDB aggregation pipelines — grouping, counting, joining collections, computing totals.

Example: count leads by status

[
  { "$group": { "_id": "$status", "count": { "$sum": 1 } } },
  { "$sort": { "count": -1 } }
]
Enter fullscreen mode Exit fullscreen mode

Pipelines can include $match, $lookup (joins), $project, $unwind, and more. Each stage output becomes the input for the next.


Free Workflow: Webhook → MongoDB Lead Capture

This workflow receives a lead via webhook, validates the email field is present, and inserts the document into MongoDB. Copy the JSON below and import it in n8n (Import → Paste JSON).

{
  "name": "Webhook → MongoDB Lead Capture",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "mongo-lead",
        "responseMode": "responseNode"
      },
      "name": "Webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 1,
      "position": [250, 300]
    },
    {
      "parameters": {
        "conditions": {
          "string": [
            {
              "value1": "={{ $json.body.email }}",
              "operation": "isNotEmpty"
            }
          ]
        }
      },
      "name": "Email Present?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 1,
      "position": [470, 300]
    },
    {
      "parameters": {
        "operation": "insert",
        "collection": "leads",
        "fields": "email, name, source, createdAt",
        "options": {}
      },
      "name": "Insert Lead",
      "type": "n8n-nodes-base.mongoDb",
      "typeVersion": 1,
      "position": [700, 200],
      "credentials": {
        "mongoDb": {
          "name": "MongoDB Atlas"
        }
      }
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={ \"status\": \"ok\", \"id\": \"{{ $json._id }}\" }"
      },
      "name": "Respond OK",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1,
      "position": [920, 200]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={ \"error\": \"email required\" }",
        "options": { "responseCode": 400 }
      },
      "name": "Respond 400",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1,
      "position": [700, 420]
    }
  ],
  "connections": {
    "Webhook": { "main": [[{ "node": "Email Present?", "type": "main", "index": 0 }]] },
    "Email Present?": {
      "main": [
        [{ "node": "Insert Lead", "type": "main", "index": 0 }],
        [{ "node": "Respond 400", "type": "main", "index": 0 }]
      ]
    },
    "Insert Lead": { "main": [[{ "node": "Respond OK", "type": "main", "index": 0 }]] }
  }
}
Enter fullscreen mode Exit fullscreen mode

MongoDB Node Gotchas Cheat Sheet

Gotcha Fix
Atlas IP not whitelisted Add n8n server IP in Atlas Network Access
Special chars in password URL-encode them in the connection string
Update replaces whole doc Always use $set operator
Delete runs on all docs Always set a query filter
_id is ObjectId, not string Use { "$oid": "..." } syntax when filtering by _id
Self-hosted not reachable Set bindIp: 0.0.0.0 in mongod.conf + open port 27017
Large query returns all docs Set a Limit to avoid memory issues

Want More Pre-Built n8n Workflows?

I package common automation patterns (Stripe → CRM, form → Google Sheets, scheduled reports, error alerting) into ready-to-import JSON files so you skip the 2-hour build-from-scratch process.

n8n Workflow Starter Pack ($29) → pirateprentice.gumroad.com/l/sxcoe

Every workflow is tested, documented, and comes with setup instructions. One-time purchase, instant download.


What do you store in MongoDB and automate with n8n? Drop your use case in the comments — I'll tell you which nodes to chain.

Top comments (1)

Collapse
 
pirateprentice profile image
Pirate Prentice

MongoDB connection tip for n8n 🍃

If you're using MongoDB Atlas, the connection string format is:

mongodb+srv://username:password@cluster0.xxxxx.mongodb.net/yourdb?retryWrites=true&w=majority
Enter fullscreen mode Exit fullscreen mode

Two gotchas that trip people up:

  1. IP allowlist — Atlas blocks connections by default. In Atlas → Network Access, add 0.0.0.0/0 (allow all) for testing, then lock it down to your n8n server IP in production.
  2. DB name in URI — the /yourdb part of the URI sets the default database; if you leave it blank, queries targeting a named collection may fail.

Which MongoDB operation do you reach for most in n8n — Find, Insert, or Aggregate?