0

How can I work with complex types in Spring Data + Mongo?

Like:

class Person {

    @Id
    String id;
    String name;
    //What can I do?
    Address address
    //OR
    String adressId;
}

How can I build this object for server side use?

I want to use adressId, but I don't know how to proceed when I need to use the address within some method.

For example:

void doWithPerson(Person person){

    System.out.println(person.getAdress());//this doesn't exist with adressId
}

Edit:

I want the mongo object as:

{
  id: 1
  name: 'Test'
  addressId: 1//not the complext object
}

and in addressCollection:

{
  id: 1
  address: 'Some info'
}

1 Answer 1

1

You can use @DBRef annotation to store reference of another object into your class object, e.g.:

@DBRef(lazy = true)
Address address;

This way, you can find the Person with particular address id. You can also retrieve Address objects independently by using mongo repository for Address class.

Here is the documentation.

Sign up to request clarification or add additional context in comments.

4 Comments

But, my mongo object will be { id: '1', name: 'Name', adressId: '1' } or { id: '1', name: 'Name', adress: {//object} }
With @DBef, your mongo object will be {id : 1, address : {$ref : address, $id : addressId}}
Is the same for collections? There is some way to clean this {$ref ... object?
You don't need to worry about it, spring data will take care of it for you. And yes, it's already clean as it just stores the id reference and not the whole object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.