Question

I'm still trying to get my hands around mongodb and how best Entities can be mapped. if you take for example: the entity user and the entity addresses. there could be one-to-many when someone is coming from jpa background. Here in mongo i don't want to use dbref. So addresses are in a Set collection in user.

Supposing i was using spring-data-mongo:

Question 1 : should both User and Address have the @Document annotation?Or just User?

Question 2 : what is the best way to query for addresses of a user. It is possible at first place? Because right now I query to get the User by username or Id and then get the addresses of the user.Can I query directly for sub-document? if yes how is it done using spring-data-mongo Criteria Query:

@Document
public class User{
    @Id
    private Long ID;
    private String username;
    private Set<Address> addresses = new HashSet<Address>();
    ...
} 

@Document
public class Address {
   @Id
   private Long ID;
   private String city;
   private String line1;
   ...

}
Was it helpful?

Solution

Question 1: No, @Document is not strictly necessary at all. We just leverage this on application startup if you activate classpath-scanning for document classes. If you don't the persistence metadata scanning will be done on the first persistence operation. We traverse properties of domain objects then, so Address will be discovered.

Question 2: You'll have to read the User objects entirely as MongoDB currently does not allow returning sub-documents. So you'll have to query for the entire Userdocument but can restrict the fields being returned to the addresses field using a fieldSpec on the Query object or the repository abstraction's @Query annotation (see ref docs).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top