mongodbunionspring-mongo

How to write union queries in mongoDB


Is it possible to write union queries in Mongo DB using 2 or more collections similar to SQL queries?

I'm using spring mongo template and in my use case, I need to fetch the data from 3-4 collections based on some conditions. Can we achieve this in a single operation?

For example, I have a field named "circuitId" which is present in all 4 collections. And I need to fetch all records from all 4 collections for which that field matches with a given value.


Solution

  • Unfortunately document based MongoDB doesn't support JOINS/Unions as in Relational DB engines. One of the key design principles on MongoDB is to prevent joins using embedded documents as per your application's data fetch patterns. Having said that, you will need to manage the logic in your application end if you really need to use the 4 collections or you may redesign your DB design as per MongoDB best practices.

    For more info : https://docs.mongodb.com/master/core/data-model-design/