---
title: "Syncing MongoDB Data to Mixpanel: A Scheduled Integration Approach"
description: Sync MongoDB data to Mixpanel for analytics using a Node.js script and scheduled tasks to handle connectivity constraints and ensure reliable data syncing.
image: https://optiblack.com/hubfs/Optiblack%20Vishal%20Rewari%20Product%20Analytics%20(33).png
---

OPTIBLACK

- [Services](https://optiblack.com/services)
- [Customers](https://optiblack.com/customers)

[Book a strategy call](https://optiblack.com/book-a-call)

- [Services](https://optiblack.com/services)
- [Customers](https://optiblack.com/customers)

[Book a strategy call](https://optiblack.com/book-a-call)

[Information](https://optiblack.com/insights/tag/information) [Resources](https://optiblack.com/insights/tag/resources) [mixpanel](https://optiblack.com/insights/tag/mixpanel) Aug 30, 2025, 12:39:42 PM · 4 min read

# Syncing MongoDB Data to Mixpanel: A Scheduled Integration Approach

![Aswin Kumar](https://optiblack.com/hubfs/T03B5CKT6HZ-U07FHH1ESR0-561cebd6e111-512.jpeg)

Aswin Kumar

Optiblack

![mongodb, mixpanel, optiblack](https://optiblack.com/hubfs/Optiblack%20Vishal%20Rewari%20Product%20Analytics%20(33).png)

This technical blog outlines a solution to sync user profiles and events from a MongoDB database to Mixpanel for analytics. Due to connectivity constraints, we implemented a Node.js script that periodically checks for updated or new data and forwards it to Mixpanel. Below, I detail the investigation, schema requirements, and implementation with sanitized code snippets using dummy database and collection names.

## **Investigation: Real-Time Feasibility**

We first explored real-time data syncing:

- **MongoDB Change Streams**: We checked if the database supported change streams by running rs.status() in the MongoDB shell. The response indicated no replica set, ruling out real-time streaming.
- **Fallback Approach**: Without replica sets, we opted for a scheduled task to query recent data, relying on timestamps in the schema.

## **Schema Requirements**

The MongoDB collections must include:

- created\_at: ISODate timestamp for new records.
- updated\_at: ISODate timestamp for updates. These fields enable filtering records modified within a specific time window (e.g., last 15 minutes).
- **Collections**: 
    - mixpanel\_users: Stores user profiles (e.g., name, email, user\_id, properties).
    - mixpanel\_events: Stores events (e.g., event\_name, user\_id, event\_properties).

## **Solution Overview**

We built a Node.js script that:

1. Connects to MongoDB (dummy name: "app\_db").
2. Queries mixpanel\_users and mixpanel\_events for records with created\_at or updated\_at within the last 15 minutes.
3. Sends user profiles to Mixpanel's People API.
4. Sends events to Mixpanel's Events API.
5. Runs every 15 minutes via a cron job and on startup for initial sync.

The script uses mongodb, node-cron, and fetch, with secrets managed via environment variables.

 

 

![Screenshot 2025-08-30 at 12.25.32](https://optiblack.com/hs-fs/hubfs/Screenshot%202025-08-30%20at%2012.25.32.png?width=509&height=779&name=Screenshot%202025-08-30%20at%2012.25.32.png)

## **Implementation**

### **Prerequisites**

- Node.js 14+.
- Dependencies: npm install dotenv mongodb node-cron.
- Environment variables (e.g., in a secure vault, not .env for production): 
    - MONGODB\_URI: MongoDB connection string (e.g., mongodb://user:pass@host:port/app\_db).
    - MIXPANEL\_PROJECT\_TOKEN: Mixpanel token.
    - MIXPANEL\_PROJECT\_ID: Mixpanel project ID.
    - MIXPANEL\_SERVICE\_USER and MIXPANEL\_SERVICE\_SECRET: For People API authentication.

### **Core Script**

This script (e.g., index.js) handles data syncing and scheduling.

require("dotenv").config();

const { MongoClient } = require("mongodb");

const cron = require("node-cron");

 

const uri = process.env.MONGODB\_URI;

 

async function processData() {

  const client = new MongoClient(uri);

  try {

    await client.connect();

    const db = client.db("app\_db"); // Dummy DB name

    console.log("Connected to MongoDB");

 

    const fifteenMinutesAgo = new Date(Date.now() - 15 \* 60 \* 1000);

    console.log(\`Processing data since ${fifteenMinutesAgo.toISOString()}\`);

 

    // Process users

    const users = await db

      .collection("mixpanel\_users")

      .find({

        $or: \[

          { updated\_at: { $gte: fifteenMinutesAgo } },

          { created\_at: { $gte: fifteenMinutesAgo } },

        \],

      })

      .toArray();

 

    for (const user of users) {

      const rawProps = JSON.parse(user.properties || "{}");

      const userProps = {

        $name: rawProps.name || "",

        $email: rawProps.email || "",

        $created: rawProps.created\_at || Math.floor(Date.now() / 1000),

        $user\_id: user.user\_id || user.uuid || "",

      };

      await sendToMixpanelProfile(user.user\_id || user.uuid, userProps);

    }

 

    // Process events

    const events = await db

      .collection("mixpanel\_events")

      .find({

        $or: \[

          { updated\_at: { $gte: fifteenMinutesAgo } },

          { created\_at: { $gte: fifteenMinutesAgo } },

        \],

      })

      .toArray();

 

    for (const event of events) {

      const props = JSON.parse(event.event\_properties || "{}");

      await sendToMixpanel(

        event.event\_name || "Unknown Event",

        event.user\_id || event.uuid,

        props,

        event.created\_at || event.updated\_at || Math.floor(Date.now() / 1000)

      );

    }

 

    console.log(\`Processed ${users.length} users and ${events.length} events\`);

  } catch (error) {

    console.error("Error:", error);

  } finally {

    await client.close();

  }

}

 

// Schedule every 15 minutes

cron.schedule("\*/15 \* \* \* \*", () =\> {

  console.log("Running cron at", new Date().toISOString());

  processData();

});

 

// Run on startup

processData();

### **Mixpanel API Helpers**

These functions send data to Mixpanel's EU endpoints.

 

async function sendToMixpanel(eventName, distinctId, props, time) {

  const payload = {

    event: eventName,

    properties: {

      token: process.env.MIXPANEL\_PROJECT\_TOKEN,

      distinct\_id: distinctId,

      time: Math.floor(new Date(time).getTime() / 1000),

      $insert\_id: Buffer.from(\`${distinctId}${eventName}${time}\`).toString("base64"),

      ...props,

    },

  };

 

  const response = await fetch("https://api-eu.mixpanel.com/track", {

    method: "POST",

    headers: { "Content-Type": "application/json" },

    body: JSON.stringify(\[payload\]),

  });

 

  const text = await response.text();

  console.log(\`Sent event: ${eventName} | Response: ${text}\`);

}

 

async function sendToMixpanelProfile(distinctId, props) {

  const payload = {

    $token: process.env.MIXPANEL\_PROJECT\_TOKEN,

    $distinct\_id: distinctId,

    $set: props || {},

    $ip: "0",

  };

 

  const response = await fetch("https://api-eu.mixpanel.com/engage", {

    method: "POST",

    headers: { "Content-Type": "application/json" },

    body: JSON.stringify(\[payload\]),

  });

 

  const text = await response.text();

  console.log(\`Sent profile: ${distinctId} | Response: ${text}\`);

}

## **Use Cases**

- **User Profiles**: Syncs name, email, and creation time to Mixpanel People for user analytics.
- **Events**: Tracks actions (e.g., "Signed Up", "Clicked Button") with custom properties.
- **Compliance**: Uses Mixpanel's EU endpoint for data residency requirements.
- **Reliability**: Handles connectivity issues via scheduled runs and idempotent requests ($insert\_id).

## **Enhancements**

- Add retry logic for failed API calls.
- Monitor with alerts for errors.
- Scale by adjusting cron frequency or batch sizes.

This solution ensures reliable data syncing for analytics while adapting to database constraints.

![Aswin Kumar](https://optiblack.com/hubfs/T03B5CKT6HZ-U07FHH1ESR0-561cebd6e111-512.jpeg)

Aswin Kumar

Tech @ Optiblack

[#Information](https://optiblack.com/insights/tag/information) [#Resources](https://optiblack.com/insights/tag/resources) [#mixpanel](https://optiblack.com/insights/tag/mixpanel)

/ Keep reading

## More from Optiblack

[![From Zero to a Multi-Region Analytics Backbone: How OptiBlack Built Scrut's Entire Data Platform](https://optiblack.com/hubfs/Optiblack%20Vishal%20Rewari%20Product%20Analytics%20(12)-3.png) Case Studies From Zero to a Multi-Region Analytics Backbone: How OptiBlack Built Scrut's Entire Data Platform](https://optiblack.com/insights/from-zero-to-a-multi-region-analytics-backbone-how-optiblack-built-scruts-entire-data-platform) [![AI in Geographic Segmentation: Key Use Cases](https://optiblack.com/hubfs/Optiblack%20Vishal%20Rewari%20Product%20Analytics%20(11)-4.png) Information AI in Geographic Segmentation: Key Use Cases](https://optiblack.com/insights/ai-geographic-segmentation-key-use-cases) [![RealBooks Selects Optiblack as Strategic Analytics Partner to Build Modern Data Stack for Real Estate Investors](https://optiblack.com/hubfs/Optiblack%20Vishal%20Rewari%20Product%20Analytics%20(11)-3.png) News RealBooks Selects Optiblack as Strategic Analytics Partner to Build Modern Data Stack for Real Estate Investors](https://optiblack.com/insights/realbooks-selects-optiblack-as-strategic-analytics-partner-to-build-modern-data-stack-for-real-estate-investors)

/ 15-minute exploration call

## Turn these insights into revenue.

We'll go through your CRM, product, and analytics data together and show you exactly where growth is leaking. No setup. No dashboards. Just signal.

[Book a strategy call →](https://optiblack.com/book-a-call)

[OPTIBLACK](https://optiblack.com/)

 US: 1309 Coffeen Ave, Suite 1200, Sheridan, WY 82801 · +1 682 297 2970 — India: 297 Designs, 74 SBK Society, Paldi, Ahmedabad 380007 · +91 9819394297

 Services

[Data services](https://optiblack.com/services) [CRM services](https://optiblack.com/services) [AI services](https://optiblack.com/services) [Book a call](https://optiblack.com/services)

 Company

[Customers](https://optiblack.com/customers) [About Us](https://optiblack.com/about-us) [Insights](https://optiblack.com/insights)

 © 2026 Optiblack · 2× Mixpanel Partner of the Year · vishal@optiblack.com

```json
{
  "@context" : "https://schema.org",
  "@type" : "BlogPosting",
  "author" : {
    "@type" : "Person",
    "name" : "Aswin Kumar",
    "url" : "https://optiblack.com/insights/author/aswin-kumar"
  },
  "dateModified" : "2025-10-20T11:17:18.847Z",
  "datePublished" : "2025-08-30T07:09:42.000Z",
  "headline" : "Syncing MongoDB Data to Mixpanel: A Scheduled Integration Approach",
  "image" : [ "https://optiblack.com/hubfs/Optiblack%20Vishal%20Rewari%20Product%20Analytics%20(33).png" ],
  "mainEntityOfPage" : {
    "@id" : "https://optiblack.com/insights/syncing-mongodb-data-to-mixpanel-a-scheduled-integration-approach",
    "@type" : "WebPage"
  },
  "publisher" : {
    "@type" : "Organization",
    "logo" : {
      "@type" : "ImageObject",
      "url" : "https://optiblack.com/hubfs/Group%201234.png"
    },
    "name" : "Optiblack"
  }
}
```