How to join multiple collections and do queries?

I’m not pretty sure could I do this. My application(buy and sell) have around five to ten categories

eg: vehicles, real estate, and cloths

I thought of creating separate MongoDB collections for each category because each of the categories contains different fields

eg: vehicle[km, body type, brand], cloths[size, colour, gender]

, This would be very easy to manage and scale.

Now can I able to send one query to those multiple collections at once

  1. sort new ads - sort all new ads from all multiple collections in order
  2. text search on field eg: title on all collections

server: nodejs

Better to keep all vehicles in one collection and add a vehicle_type field. Then you can query on all vehicles without joins but also select groups of vehicle types.

already vehicles is a single collection but I need to send a full text search quries to all my collections which contains real estate, cloths and others

You can put all items (vehicles, real estate, clothes, etc) into a single collection as MongoDB does not force all documents to have the same schema. You would need to make sure your code properly handled the differences when trying to display that data. You would also need to make sure that any indexes you created took into account the differences in schema to make your queries as efficient as possible.

2 Likes

Hi! If you were to put all of these categories in a single collection, you could easily do a search query across categories in 1 query. The index for Search is created per collection and must be used in the first stage of the aggregation ($searchBeta), and it cannot be used in a $lookup pipeline. Here are more details for that: https://docs.atlas.mongodb.com/reference/atlas-search/query-syntax/#behavior

2 Likes