How to get data from two collections in spring usi

2019-09-06 16:57发布

问题:

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:

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:"abc1@gmail.com",mobile:123],[email:"abc2@gmail.com",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.