icon Join with us for Oracle DBA Training Live Session ENROLL NOW

Social Media Analytics Tool: Finding the Best Posting Times with MongoDB Aggregation Pipelines

Breadcrumb Abstract Shape
Breadcrumb Abstract Shape
Breadcrumb Abstract Shape
Breadcrumb Abstract Shape
Breadcrumb Abstract Shape
Breadcrumb Abstract Shape
Social Media Analytics Tool using MongoDB aggregation pipelines to find the best posting times
  • 16 Nov, 2026
  • 0 Comments
  • 12 Mins Read

Social Media Analytics Tool: Finding the Best Posting Times with MongoDB Aggregation Pipelines

Social Media Analytics Tool: Finding the Best Posting Times with MongoDB Aggregation Pipelines

Introduction

Social media success is not only about creating high-quality content. When you publish a post can have a significant impact on its reach, impressions, engagement, and overall performance.

A post published when the target audience is highly active can generate significantly more likes, comments, shares, clicks, and impressions than the same post published at an inactive time.

This makes posting-time analysis an important part of social media analytics.

In this project, we will build a Social Media Analytics Tool using MongoDB aggregation pipelines. The tool analyzes historical social media post-performance data and identifies the days and time periods that generate the highest engagement.

This project demonstrates how MongoDB aggregation stages such as $match, $group, $set, $project, $sort, and date operators can transform raw social media data into useful business insights.

What Is a Social Media Analytics Tool?

A Social Media Analytics Tool collects and analyzes performance data generated by social media posts.

A typical post may contain information such as:

  • Social media platform
  • Post type
  • Posting date and time
  • Impressions
  • Likes
  • Comments
  • Shares
  • Clicks
  • Engagement rate
  • Hashtags
  • Audience information

By analyzing this historical data, businesses can answer questions such as:

  • Which day generates the most engagement?
  • What time should we publish?
  • Which platform performs best?
  • Which content type generates the most interactions?
  • What are the best posting hours?
  • Which posts have the highest engagement rate?

MongoDB is well suited for this type of application because social media data can contain flexible and evolving fields.

Project Objective

The primary objective of this project is to create a system that analyzes historical social media posts and recommends the best posting times.

For example, the analytics system could produce results like:

Day Time Slot Posts Average Engagement
Tuesday 10 AM 45 8.7%
Wednesday 6 PM 52 9.3%
Thursday 7 PM 48 10.1%
Friday 11 AM 39 7.9%

Based on this analysis, the application could recommend:

Thursday between 7 PM and 8 PM is the best-performing posting window.

Why Use MongoDB for Social Media Analytics?

Social media data is often semi-structured.

For example, an Instagram post might contain:

{
  "platform": "Instagram",
  "contentType": "video",
  "hashtags": ["mongodb", "database"],
  "metrics": {
    "likes": 850,
    "comments": 72,
    "shares": 125
  }
}

A LinkedIn post could contain a slightly different structure:

{
  "platform": "LinkedIn",
  "contentType": "carousel",
  "metrics": {
    "likes": 420,
    "comments": 35,
    "shares": 60,
    "clicks": 180
  }
}

MongoDB’s document model allows these different structures to coexist within the same collection.

The aggregation framework can then process this data and calculate meaningful statistics.

High-Level System Architecture

A simple architecture for the project can look like this:

Social Media Platforms
        |
        v
 Data Collection Layer
        |
        v
     MongoDB
        |
        v
Aggregation Pipeline
        |
        v
   Analytics API
        |
        v
Dashboard / Reports

The data collection layer stores social media performance data in MongoDB.

The aggregation pipeline processes the historical data.

The backend API provides the analytics results to the frontend dashboard.

The dashboard then displays charts, tables, and posting-time recommendations.

Designing the MongoDB Collection

Let’s create a collection called:

social_posts

Each document represents one social media post.

A basic document could look like this:

{
  "_id": ObjectId("672001"),
  "platform": "Instagram",
  "contentType": "video",
  "postedAt": ISODate("2026-10-15T18:30:00Z"),
  "metrics": {
    "impressions": 25000,
    "likes": 1800,
    "comments": 145,
    "shares": 320,
    "clicks": 850
  }
}

Another document could represent a LinkedIn post:

{
  "_id": ObjectId("672002"),
  "platform": "LinkedIn",
  "contentType": "carousel",
  "postedAt": ISODate("2026-10-16T10:00:00Z"),
  "metrics": {
    "impressions": 12000,
    "likes": 560,
    "comments": 75,
    "shares": 90,
    "clicks": 410
  }
}

Understanding the Important Fields

platform

Identifies the social media platform.

Examples include:

Instagram
LinkedIn
Facebook
X
YouTube

contentType

Identifies the type of content published.

Examples include:

image
video
carousel
text
reel
article

postedAt

Stores the exact date and time when the post was published.

This is one of the most important fields because the aggregation pipeline needs to extract:

  • Day of the week
  • Posting hour
  • Date
  • Time period

metrics

Contains performance statistics such as:

  • Impressions
  • Likes
  • Comments
  • Shares
  • Clicks

Calculating Engagement

A simple way to calculate total engagement is:

Engagement =
Likes + Comments + Shares + Clicks

For example:

Likes      = 500
Comments  = 50
Shares    = 80
Clicks    = 120

Total Engagement = 750

However, comparing raw engagement numbers can sometimes be misleading.

A post with 100,000 impressions naturally has more opportunities to generate interactions than a post with 2,000 impressions.

Therefore, an engagement rate is often more useful.

Calculating Engagement Rate

A simple engagement-rate formula is:

Engagement Rate =
(Likes + Comments + Shares + Clicks) / Impressions × 100

For example:

Likes        = 500
Comments    = 50
Shares      = 80
Clicks      = 120
Impressions = 10,000

Total engagement:

500 + 50 + 80 + 120 = 750

Engagement rate:

750 / 10,000 × 100 = 7.5%

This gives the analytics system a standardized metric for comparing posts.

Building the MongoDB Aggregation Pipeline

MongoDB aggregation pipelines process documents through multiple stages.

A typical pipeline for this project can follow this structure:

$match
   |
   v
$set
   |
   v
$group
   |
   v
$project
   |
   v
$sort

Each stage performs a specific operation.

Step 1: Filter Relevant Posts with $match

Suppose we want to analyze only Instagram posts.

db.social_posts.aggregate([
  {
    $match: {
      platform: "Instagram"
    }
  }
])

The $match stage filters documents before the remaining aggregation stages execute.

We can also filter posts by a specific date range:

{
  $match: {
    platform: "Instagram",
    postedAt: {
      $gte: ISODate("2026-01-01T00:00:00Z"),
      $lt: ISODate("2026-11-01T00:00:00Z")
    }
  }
}

Filtering early can reduce the amount of data processed by later stages.

Step 2: Extract the Posting Day and Hour

Now we need to determine when each post was published.

MongoDB provides date operators that can extract the hour and day of the week.

{
  $set: {
    postingHour: {
      $hour: "$postedAt"
    },
    dayOfWeek: {
      $dayOfWeek: "$postedAt"
    }
  }
}

MongoDB represents the days of the week numerically:

1 = Sunday
2 = Monday
3 = Tuesday
4 = Wednesday
5 = Thursday
6 = Friday
7 = Saturday

Step 3: Calculate Total Engagement

Next, we can calculate total engagement using $add.

{
  $set: {
    totalEngagement: {
      $add: [
        "$metrics.likes",
        "$metrics.comments",
        "$metrics.shares",
        "$metrics.clicks"
      ]
    }
  }
}

A document could now contain:

{
  "platform": "Instagram",
  "postingHour": 18,
  "dayOfWeek": 4,
  "totalEngagement": 2350
}

Step 4: Calculate Engagement Rate

Now we can calculate the engagement rate using $divide and $multiply.

{
  $set: {
    engagementRate: {
      $multiply: [
        {
          $divide: [
            "$totalEngagement",
            "$metrics.impressions"
          ]
        },
        100
      ]
    }
  }
}

For example:

Total Engagement = 2,350
Impressions      = 25,000

Engagement Rate = 9.4%

Step 5: Group Posts by Posting Time

Now we can group posts according to their posting hour.

For example:

10 AM → 45 posts
11 AM → 52 posts
12 PM → 37 posts
6 PM  → 68 posts
7 PM  → 72 posts

We can use $group:

{
  $group: {
    _id: "$postingHour",
    totalPosts: {
      $sum: 1
    },
    averageEngagementRate: {
      $avg: "$engagementRate"
    },
    totalEngagement: {
      $sum: "$totalEngagement"
    }
  }
}

MongoDB will calculate aggregate statistics for each posting hour.

Grouping by Day and Hour

A more useful analysis is to combine both the day and the hour.

{
  $group: {
    _id: {
      dayOfWeek: "$dayOfWeek",
      postingHour: "$postingHour"
    },
    totalPosts: {
      $sum: 1
    },
    averageEngagementRate: {
      $avg: "$engagementRate"
    }
  }
}

The result could look like:

Tuesday    10 AM   8.2%
Tuesday    11 AM   7.6%
Wednesday   6 PM   9.1%
Thursday    7 PM  10.4%
Friday     11 AM   8.3%

This provides much more useful information than simply identifying the best hour.

Converting Day Numbers into Day Names

Instead of displaying:

2
3
4
5

we can convert these values into readable day names using $switch.

{
  $set: {
    dayName: {
      $switch: {
        branches: [
          { case: { $eq: ["$_id.dayOfWeek", 1] }, then: "Sunday" },
          { case: { $eq: ["$_id.dayOfWeek", 2] }, then: "Monday" },
          { case: { $eq: ["$_id.dayOfWeek", 3] }, then: "Tuesday" },
          { case: { $eq: ["$_id.dayOfWeek", 4] }, then: "Wednesday" },
          { case: { $eq: ["$_id.dayOfWeek", 5] }, then: "Thursday" },
          { case: { $eq: ["$_id.dayOfWeek", 6] }, then: "Friday" },
          { case: { $eq: ["$_id.dayOfWeek", 7] }, then: "Saturday" }
        ],
        default: "Unknown"
      }
    }
  }
}

This makes the output easier for users to understand.

Formatting the Final Result with $project

We can use $project to return only the fields required by the dashboard.

{
  $project: {
    _id: 0,
    day: "$dayName",
    postingHour: "$_id.postingHour",
    totalPosts: 1,
    averageEngagementRate: 1
  }
}

The result is now clean and easy for an application or frontend to consume.

Sorting the Best Posting Times

Finally, we can sort the results by engagement rate.

{
  $sort: {
    averageEngagementRate: -1
  }
}

The highest-performing posting times will appear first.

For example:

Thursday    7 PM   10.4%
Wednesday   6 PM    9.8%
Tuesday    10 AM    9.2%
Friday     11 AM    8.7%
Monday      6 PM    8.1%

The application can now recommend Thursday at 7 PM as the best posting window.

Complete Aggregation Pipeline

A complete pipeline could look like this:

db.social_posts.aggregate([
  {
    $match: {
      platform: "Instagram"
    }
  },
  {
    $set: {
      postingHour: {
        $hour: "$postedAt"
      },
      dayOfWeek: {
        $dayOfWeek: "$postedAt"
      },
      totalEngagement: {
        $add: [
          "$metrics.likes",
          "$metrics.comments",
          "$metrics.shares",
          "$metrics.clicks"
        ]
      }
    }
  },
  {
    $set: {
      engagementRate: {
        $multiply: [
          {
            $divide: [
              "$totalEngagement",
              "$metrics.impressions"
            ]
          },
          100
        ]
      }
    }
  },
  {
    $group: {
      _id: {
        dayOfWeek: "$dayOfWeek",
        postingHour: "$postingHour"
      },
      totalPosts: {
        $sum: 1
      },
      averageEngagementRate: {
        $avg: "$engagementRate"
      }
    }
  },
  {
    $set: {
      dayName: {
        $switch: {
          branches: [
            { case: { $eq: ["$_id.dayOfWeek", 1] }, then: "Sunday" },
            { case: { $eq: ["$_id.dayOfWeek", 2] }, then: "Monday" },
            { case: { $eq: ["$_id.dayOfWeek", 3] }, then: "Tuesday" },
            { case: { $eq: ["$_id.dayOfWeek", 4] }, then: "Wednesday" },
            { case: { $eq: ["$_id.dayOfWeek", 5] }, then: "Thursday" },
            { case: { $eq: ["$_id.dayOfWeek", 6] }, then: "Friday" },
            { case: { $eq: ["$_id.dayOfWeek", 7] }, then: "Saturday" }
          ],
          default: "Unknown"
        }
      }
    }
  },
  {
    $project: {
      _id: 0,
      day: "$dayName",
      postingHour: "$_id.postingHour",
      totalPosts: 1,
      averageEngagementRate: 1
    }
  },
  {
    $sort: {
      averageEngagementRate: -1
    }
  }
])

Adding Time Slots

Instead of displaying individual hours, the analytics dashboard can group posting times into broader time slots.

For example:

Morning     → 6 AM – 11 AM
Afternoon   → 12 PM – 4 PM
Evening     → 5 PM – 8 PM
Night       → 9 PM – 11 PM

We can create a time-slot field using $switch.

{
  $set: {
    timeSlot: {
      $switch: {
        branches: [
          {
            case: {
              $and: [
                { $gte: ["$postingHour", 6] },
                { $lt: ["$postingHour", 12] }
              ]
            },
            then: "Morning"
          },
          {
            case: {
              $and: [
                { $gte: ["$postingHour", 12] },
                { $lt: ["$postingHour", 17] }
              ]
            },
            then: "Afternoon"
          },
          {
            case: {
              $and: [
                { $gte: ["$postingHour", 17] },
                { $lt: ["$postingHour", 21] }
              ]
            },
            then: "Evening"
          }
        ],
        default: "Night"
      }
    }
  }
}

This allows the application to provide recommendations at a broader level.

Comparing Different Social Media Platforms

The same aggregation approach can compare multiple platforms.

For example:

Instagram → 9.4%
LinkedIn  → 8.7%
Facebook  → 6.9%
X         → 5.8%

We can group posts by platform:

{
  $group: {
    _id: "$platform",
    averageEngagementRate: {
      $avg: "$engagementRate"
    },
    totalPosts: {
      $sum: 1
    }
  }
}

This helps businesses understand which platforms generate the strongest engagement.

Finding the Best Content Type

Posting time is only one factor that affects performance.

Content type can also have a significant impact.

We can group posts by contentType:

{
  $group: {
    _id: "$contentType",
    averageEngagementRate: {
      $avg: "$engagementRate"
    },
    totalPosts: {
      $sum: 1
    }
  }
}

The result might look like:

Video      → 11.2%
Carousel   → 9.8%
Image      → 7.4%
Text       → 5.9%

The analytics tool could therefore recommend both:

When to post

and

What type of content to post.

Finding Top-Performing Posts

The same dataset can be used to identify individual high-performing posts.

db.social_posts.aggregate([
  {
    $set: {
      totalEngagement: {
        $add: [
          "$metrics.likes",
          "$metrics.comments",
          "$metrics.shares",
          "$metrics.clicks"
        ]
      }
    }
  },
  {
    $sort: {
      totalEngagement: -1
    }
  },
  {
    $limit: 10
  }
])

This returns the top 10 posts based on total engagement.

Building a Posting-Time Recommendation System

Once the aggregation pipeline identifies high-performing time slots, the application can create recommendations.

For example:

Recommended Platform: LinkedIn

Best Day:
Thursday

Best Time:
6:00 PM – 7:00 PM

Average Engagement Rate:
10.4%

Recommended Content:
Carousel

The recommendation can be generated dynamically from MongoDB analytics.

Handling Time Zones

Time zones are extremely important in social media analytics.

A post stored in UTC may not represent the user’s local posting time.

For example:

UTC: 13:30
IST: 19:00

If the target audience is in India, analyzing the UTC hour directly could produce misleading results.

MongoDB supports timezone-aware date operations.

For example:

{
  $hour: {
    date: "$postedAt",
    timezone: "Asia/Kolkata"
  }
}

This allows the analytics system to analyze posting times according to the target audience’s timezone.

For a global application, the timezone can be stored with the account or audience configuration.

Handling Low Sample Sizes

Suppose the analytics tool reports:

Sunday 2 AM → 15% engagement

That sounds excellent.

But what if only one post was published at that time?

That result should not automatically become the recommendation.

We can require a minimum number of posts.

For example:

{
  $match: {
    totalPosts: {
      $gte: 10
    }
  }
}

This ensures that recommendations are based on a reasonable amount of historical data.

A high average based on very few observations may not be a reliable recommendation.

Improving the Recommendation Model

A production-level system can consider additional factors instead of relying only on average engagement rate.

The recommendation model could consider:

  • Number of posts
  • Average impressions
  • Engagement rate
  • Click-through rate
  • Shares
  • Comments
  • Content type
  • Platform
  • Audience timezone
  • Recent performance

A weighted score could then be calculated.

For example:

Recommendation Score =
40% Engagement Rate
+ 25% Impressions
+ 20% Shares
+ 15% Clicks

This creates a more sophisticated recommendation engine.

Dashboard Design

The frontend can display the analytics through a simple dashboard.

KPI Cards

Total Posts
12,540
Average Engagement
8.7%
Best Day
Thursday
Best Time
7 PM

Posting-Time Heatmap

A heatmap can show engagement across different days and hours.

          9AM  12PM  3PM  6PM  9PM

Mon        â–‘    â–’     â–’    â–“    â–‘
Tue        â–’    â–“     â–“    â–“    â–’
Wed        â–’    â–“     â–“    â–ˆ    â–“
Thu        â–“    â–“     â–“    â–ˆ    â–ˆ
Fri        â–’    â–’     â–“    â–“    â–’
Sat        â–‘    â–’     â–’    â–“    â–’
Sun        â–‘    â–‘     â–’    â–’    â–‘

Darker areas can represent higher engagement.

This gives marketers a quick visual representation of the best posting windows.

Useful MongoDB Aggregation Operators

Several aggregation operators are particularly useful for this project.

$match

Filters documents.

{
  $match: {
    platform: "Instagram"
  }
}

$group

Groups documents and calculates statistics.

{
  $group: {
    _id: "$postingHour",
    avgEngagement: {
      $avg: "$engagementRate"
    }
  }
}

$set

Creates calculated fields.

{
  $set: {
    totalEngagement: {
      $add: [...]
    }
  }
}

$project

Controls the fields returned.

{
  $project: {
    day: 1,
    postingHour: 1
  }
}

$sort

Sorts results.

{
  $sort: {
    averageEngagementRate: -1
  }
}

$limit

Restricts the number of results.

{
  $limit: 10
}

Together, these operators allow MongoDB to perform substantial analytical processing directly inside the database.

Performance Optimization

Social media platforms can generate millions of posts.

Running complex aggregation pipelines over large collections can become expensive.

Indexes can help improve performance.

For example:

db.social_posts.createIndex({
  platform: 1,
  postedAt: 1
})

This can be useful when filtering by platform and date.

If the application frequently filters by content type as well, another index may be appropriate:

db.social_posts.createIndex({
  platform: 1,
  contentType: 1,
  postedAt: 1
})

Indexes should be created based on actual query patterns rather than adding indexes unnecessarily.

Using explain() to Analyze the Pipeline

MongoDB provides explain() for understanding query execution.

For example:

db.social_posts.explain("executionStats").aggregate([
  {
    $match: {
      platform: "Instagram"
    }
  }
])

This can help identify:

  • Documents examined
  • Keys examined
  • Execution time
  • Index usage

This becomes especially important as the dataset grows.

Possible API Response

A backend API could return a result like:

{
  "platform": "Instagram",
  "bestPostingTimes": [
    {
      "day": "Thursday",
      "time": "7 PM",
      "engagementRate": 10.4
    },
    {
      "day": "Wednesday",
      "time": "6 PM",
      "engagementRate": 9.8
    }
  ]
}

The frontend can use this data to generate charts, recommendations, and reports.

Advanced Features

Once the basic system is working, several advanced features can be added.

Audience-Specific Recommendations

Instead of finding one universal best time, recommendations can be generated for different audience segments.

For example:

India Audience → 7 PM IST
US Audience    → 9 AM EST
UK Audience    → 6 PM GMT

Platform-Specific Recommendations

Different platforms can have different optimal posting times.

For example:

LinkedIn:
Tuesday – 10 AM

Instagram:
Thursday – 7 PM

Facebook:
Wednesday – 6 PM

Content-Specific Recommendations

The system can also combine content type and posting time.

For example:

Carousel:
Thursday – 7 PM

Video:
Wednesday – 6 PM

Image:
Friday – 11 AM

This makes the recommendation engine more useful for marketing teams.

Real-World Use Cases

A Social Media Analytics Tool built with MongoDB can be useful for:

Marketing Agencies

Manage posting schedules for multiple clients.

Content Creators

Identify when their audience is most active.

E-Commerce Businesses

Optimize promotional post timing.

SaaS Companies

Analyze engagement with technical and educational content.

Influencers

Compare content types and audience engagement.

Social Media Teams

Build automated publishing schedules based on historical performance.

Challenges to Consider

Real-world social media analytics introduces several challenges.

Data Quality

Incomplete or inconsistent metrics can affect the accuracy of the results.

Time Zones

Global audiences require timezone-aware analysis.

Changing Audience Behavior

The best posting time can change over time.

Platform Differences

Each platform may calculate and expose metrics differently.

Small Sample Sizes

Recommendations based on very few posts can be unreliable.

Seasonal Effects

Holidays, events, weekends, and marketing campaigns can significantly change engagement.

Improving the System with Recent Data

Historical data from several years ago may not accurately represent current audience behavior.

A better system can give more weight to recent posts.

For example:

Last 30 days  → High weight
31–90 days    → Medium weight
90+ days      → Low weight

This allows recommendations to adapt as audience behavior changes.

Future Enhancements

The project can be extended into a complete social media intelligence platform.

Possible features include:

  • Automated data collection
  • Real-time analytics
  • AI-powered posting recommendations
  • Content performance prediction
  • Hashtag analysis
  • Sentiment analysis
  • Audience segmentation
  • Competitor analysis
  • Automated scheduling
  • Performance alerts
  • Trend detection
  • Cross-platform reporting

MongoDB can serve as the central data layer while the analytics and recommendation logic can be implemented in the application layer.

Conclusion

A Social Media Analytics Tool is a practical project for demonstrating how MongoDB can handle real-world analytical workloads.

By storing social media posts and their performance metrics in MongoDB, we can use aggregation pipelines to calculate engagement, group posts by day and hour, compare platforms, analyze content types, and identify high-performing posting windows.

The core workflow is:

Social Media Data
       ↓
     MongoDB
       ↓
    $match
       ↓
     $set
       ↓
    $group
       ↓
   $project
       ↓
     $sort
       ↓
Best Posting Times

The most important takeaway is that MongoDB aggregation is not limited to simple data retrieval. With the right pipeline, MongoDB can perform powerful analytical operations directly on large collections.

lets talk - learnomate helpdesk

Book a Free Demo

lets talk - learnomate helpdesk

Book a Free Demo