Search code examples
springmongodbspring-dataspring-data-mongodb

Update a list of objects in spring mongodb


In the below code I want to generate addrId automatically and show it in the Person document, but the addrId is not showing up in the document.

@Document
public class Person {
    
  @Id
  String id;

  List<Address> addresses;
        
 }    

public class Address {
    
    @Id
    String addrId;

    String street;
  }    


public class Example {
    
    public Person createAddress(Person person, Address addr) {
            Set<Address> addresses = new HashSet<>();
            addresses.add(addr);

    
            Query query = new Query();
            query.addCriteria(Criteria.where("id").is(id));
            Person person = mongoTemplate.findOne(query, Person.class);
            person.setAddresses(addresses);
    
            return mongoTemplate.save(person);
        }
    }

Expected document with addrId:

{
  "_id" : ObjectId("592c7029aafef820f432c5f3"),
  "_class" : "tutorial.mongodb.documents.Person",
  "addresses" : [{
    "addrId" : ObjectId("321c7029aafed220f432d321"),
    "street" : "London street"
  }]
} 

but addrId is not getting displayed as seen in the below document:

{
      "_id" : ObjectId("592c7029aafef820f432c5f3"),
      "_class" : "tutorial.mongodb.documents.Person",
      "addresses" : [{
        "street" : "London street"
      }]
    }

Solution

  • This works for me as expected:

     public String createAddress(Person person, Address addr) {
    
            addr.setAddrId(String.valueOf(UUID.randomUUID()));
    
            List<Address > addrs = person.getAddresses();
            addrs.add(addr);
    
            person.setAddresses(addrs);
            
            mongoTemplate.save(person);
    
            return addr.getAddrId();
        }