Module 4 of 6 — Advanced

Database Automation in n8n – Connect MongoDB, Firebase & Google Sheets in Real-Time Sync Workflows

Build powerful database automation workflows in n8n — sync MongoDB, Firebase Firestore, and Google Sheets in real time, with automated reporting and cross-database pipelines.

14 min read Jan 22, 2026 5 Steps Advanced Level
Step-by-Step Instructions
1
Step 1 — Set Up Database Connections

MongoDB: In n8n Credentials, create a "MongoDB" credential. Enter your MongoDB Atlas connection string: mongodb+srv://username:password@cluster.mongodb.net/dbname. The native MongoDB node supports Find, Insert, Update, Delete, and Aggregate operations.

Firebase Firestore: Download your Firebase service account JSON from Firebase Console → Project Settings → Service Accounts. Create an "HTTP Request" credential with the service account details. Use Google's Firestore REST API: https://firestore.googleapis.com/v1/projects/PROJECT_ID/databases/(default)/documents/COLLECTION. For n8n Cloud, use the native "Google Firebase Firestore" node if available, or the HTTP Request approach with a service account JWT.

Google Sheets: Use the native "Google Sheets" node with OAuth2 authentication. This is the simplest setup — just connect your Google account and select the spreadsheet. The Sheets node supports Read, Append, Update, and Delete row operations.

2
Step 2 — Build a Real-Time Sync Between MongoDB and Google Sheets

Use case: Your CRM data lives in MongoDB. Your sales team tracks deals in Google Sheets. Keep them in sync automatically.

Set up a schedule trigger (every 30 minutes or every hour). Use the MongoDB Find node to get all documents updated in the last sync window: { updatedAt: { $gte: {{ new Date(Date.now() - 3600000).toISOString() }} } }

For each document, use a Google Sheets node in "Update Row" mode to find the matching row by a unique ID column and update it. If no matching row exists (new record), use an "Append Row" operation instead.

Use a Code node to track the sync state (timestamp of last successful sync) in a MongoDB "system_metadata" collection. This prevents re-processing records that didn't change.

3
Step 3 — Firebase Firestore Real-Time Triggers

Firebase doesn't push to n8n directly, but you can create a Firebase Cloud Function that sends a webhook to n8n when a document changes. Here's the Cloud Function pattern:

// Firebase Cloud Function (JavaScript)
exports.onDocumentWrite = functions.firestore
  .document("orders/{orderId}")
  .onWrite(async (change, context) => {
    const newData = change.after.data();
    await fetch("https://your-n8n.domain/webhook/firebase-order", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        orderId: context.params.orderId,
        data: newData,
        eventType: change.before.exists ? "updated" : "created"
      })
    });
  });

In n8n, the Webhook node receives this and triggers your processing workflow. This gives you true real-time Firebase → n8n integration.

4
Step 4 — Build Automated Reporting Pipelines

Pattern: MongoDB aggregation → data transformation → Google Sheets report → email delivery.

Use the MongoDB node with an Aggregate operation to run your reporting query:

// MongoDB Aggregate Pipeline
[
  { "$match": { "createdAt": { "$gte": { "$date": "{{ startDate }}" } } } },
  { "$group": {
      "_id": "$category",
      "total_revenue": { "$sum": "$amount" },
      "order_count": { "$count": {} },
      "avg_order": { "$avg": "$amount" }
  }},
  { "$sort": { "total_revenue": -1 } }
]

The MongoDB node returns the aggregation results as n8n items. A Set node formats each item into the column structure your Google Sheet expects. The Google Sheets node appends all rows in a single operation using "Append or Update" mode.

5
Step 5 — Cross-Database Data Migration

When migrating data between databases (e.g., from Firebase to MongoDB, or from MySQL to Firebase), use n8n as the migration controller.

Use SplitInBatches node (batch size: 100) to process large datasets without timing out. Between batches, add a Wait node (2 seconds) to avoid overloading the target database.

Use a Code node to transform the source schema to the target schema — field renames, type conversions, nested structure flattening. Always validate transformed records before writing to the target.

Track migration progress in a MongoDB "migration_log" collection: record batch number, items processed, items failed, and timestamp. This lets you resume interrupted migrations without re-processing already-migrated records.

Sample Workflow Diagram
Real-World Automation Example
Real-World Example: Multi-Database E-Commerce Analytics Dashboard

An e-commerce business stores orders in MongoDB, user sessions in Firebase, and the CEO reviews all KPIs in a Google Sheets dashboard. n8n keeps all three in sync and generates a daily email report automatically.

1
Every hour: n8n fetches updated orders from MongoDB (only records changed since last sync).
2
Batch processing with SplitInBatches (50 records per batch) prevents timeout on large datasets.
3
Each batch transforms MongoDB schema to the Sheets column layout via Code node.
4
Google Sheets "Update or Append" operation: existing rows update, new rows append.
5
Daily at 8 AM: MongoDB aggregation runs revenue/order/customer analytics.
6
Results write to a "Daily Summary" sheet tab, then SendGrid delivers the CEO a formatted HTML email.
7
All sync timestamps tracked in system_metadata — interrupted syncs resume without data loss.
Frequently Asked Questions
Can n8n connect to MySQL and PostgreSQL?
Yes — n8n has native MySQL and PostgreSQL nodes that support SELECT, INSERT, UPDATE, DELETE, and raw SQL queries. These are typically the easiest databases to set up in n8n as they use simple host/port/user/password credentials rather than connection strings or service accounts.
How do I avoid duplicate records when syncing databases?
Use a unique identifier (like orderId or email) as your deduplication key. Before inserting, query the target database for an existing record with that key. If found, update it; if not, insert. n8n's "Upsert" operation (available for some nodes) does this automatically. For Google Sheets, use a unique ID column and search for it before deciding to update vs. append.
What is the largest amount of data I can process in n8n?
There is no hard data limit, but processing should be chunked into batches of 50-500 records depending on record size and transformation complexity. Use SplitInBatches to process in chunks, with Wait nodes between batches. For truly massive migrations (millions of records), run the n8n workflow multiple times with date-range partitioning rather than one giant run.