DEV Community

Cover image for How I Merged Two MongoDB Collections Using $unionWith
Akash Singh
Akash Singh

Posted on

How I Merged Two MongoDB Collections Using $unionWith

How I Merged Two MongoDB Collections Using $unionWith

While working on a doctor listing feature, I encountered an issue where some doctors were missing from the All Doctors page.

After investigating the issue, I found that data was being fetched from two separate collections, and pagination was being applied independently. This resulted in inconsistent results and unnecessary complexity.

The Problem

I had two collections:

  • ReferralUser
  • user_managements

Fetching data separately caused:

  • Multiple API calls
  • Missing records
  • Inconsistent pagination
  • Additional frontend logic

The Solution

MongoDB's $unionWith aggregation stage allowed me to combine both collections into a single pipeline.


js
`db.ReferralUser.aggregate([
  {
    $unionWith: {
      coll: "user_managements"
    }
  }
]);`
---

Benefits
Reduced multiple API calls into one
Improved pagination consistency
Simplified frontend logic
Easier to maintain
Key Takeaways

When working with similar data across multiple collections, $unionWith can help simplify the API and provide more consistent results.

Thanks for reading! 🚀
Enter fullscreen mode Exit fullscreen mode

Top comments (0)