I’m working with MongoDB and need to combine data from different collections, similar to how JOIN works in SQL databases.
Let me give you an example. I have two collections called posts
and authors
:
posts
{ author_id: 67890, post_id: 123, content: "hello world" }
{ author_id: 67890, post_id: 789, content: "test post" }
{ author_id: 11111, post_id: 123, content: "nice article" }
authors
{ author_id: 67890, username: "alice" }
{ author_id: 11111, username: "bob" }
I want to get all posts where post_id
equals 123 and include the author details for each post in a single query.
Right now I’m doing this in multiple steps. First I query posts that match my condition, then I collect all the author IDs from those results, query the authors collection separately, and finally combine everything manually. This feels inefficient and I’m wondering if there’s a better approach in MongoDB to do this all at once.
Use $lookup - it’s MongoDB’s version of SQL JOINs and perfect for combining documents from different collections. Here’s what you need: javascript db.posts.aggregate([ { $match: { post_id: 123 } }, { $lookup: { from: "authors", localField: "author_id", foreignField: "author_id", as: "author_details" } } ])
This grabs posts with post_id: 123
and pulls in the author info as an author_details
array. $match filters first, then $lookup joins based on matching author_id fields. Way cleaner than multiple queries and it’s all one database operation.
Yeah, $lookup’s your best bet here. Just watch out - it’ll crawl with large collections. Throw some indexes on those author_id fields if u haven’t already. Makes a massive difference for performance.
Oh interesting! Are you using aggregation pipeline? What are your collection sizes like - how’s the $lookup performance with larger datasets? Ever thought about just embedding author info directly in posts?