How to get data from two collections in spring using Mongotemplate or MongoRepository

1k views Asked by At

I have started working with spring and mongodb few months ago. Till now I din't get how to fetch data from multiple collection using Mongotemplate or MongoRepository. I have two collections Person and Contacts.now I want to fetch list of Customer along with Contacts. Customer is having the is is _id and Contact is having the relation id is customerId So how can i get the customer contact details of the data.

1

There are 1 answers

0
vmr On

Your data needs de-normalization, think the MongoDB way. You need to store 'Person/Customer' data along-with corresponding 'Contacts'. This is a 1:n kind of association. You can easily store required data in the following schema , below is a sample 'Person/Customer' document which embeds his 'Contact' details=>

{
 name:"abc",
 age: 35,
 Contact:{[email:"[email protected]",mobile:123],[email:"[email protected]",mobile:234]}
}

If you end up normalizing data like mentioned, you tend to throw away the powerful embedding capability that MongoDB offers and end up doing joins in code.