VOOZH about

URL: https://dev.to/akashsingh-dev/how-i-merged-two-mongodb-collections-using-unionwith-2mj9

⇱ How I Merged Two MongoDB Collections Using $unionWith - DEV Community


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! 🚀