Announcement Announcement Module
Collapse
No announcement yet.
Spring Data Mongo DB - How to update a nested object Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Spring Data Mongo DB - How to update a nested object

    I'm using Spring Data with MongoDB with the following domain model/repository. I can save/delete data in MongoDB without any issues. Hwoever, I'm having difficulty updating data.

    @Document
    class Customer {

    String ssn;
    List<Account> accounts;

    //getters ..
    //setters..
    }

    class Account {

    String accountNumber;
    String accountType;
    Double balance;
    ...
    //setters
    //getters..
    }


    @Repository
    class CustomerRepository{

    @Autowired
    private MongoTemplate mongoTemplate;

    public void updateBalance(Customer updateCustomer){
    Query findQuery = new Query(where("ssn").is(updateCustomer.getSsn()));
    Customer customerFromDB = mongoTemplate.findOne(findQuery, Customer.class, "CUSTOMERS");
    Double previousBalance = customerFromDB.getAccounts().get(0).getBalance(); //assume for simplicity
    Double newBalance = updateCustomer.getAccounts().get(0).getBalance(); //assume for simplicity

    List<Account> accounts = customerFromDB.getAccounts();
    for(Account accountToUpdate: accounts){
    //if(accountToUpdate.accountNumber matches customer's account #){
    mongoTemplate.updateFirst(findQuery, new Update().set("balance", newBalance), "CUSTOMERS");
    }
    }
    }

    ..
    The newBalance value (i.e. $200 in JSON below) is getting updated as part of the Customer data instead of the nested account array object (JSON is mentioned below). Can someone help me how I can correctly update the balance amount using Spring Data for MongoDB?

    {
    "ssn" : "12345678",
    "balance" : "200",
    "accounts" : [{
    "accountNumber" : "123456ABC",
    "accountType" : "CHK",
    "balance" : "100",
    }],

    }


    Thank you!

  • #2
    I think using "accounts[0].balance" instead of just "balance" should do the trick.

    Comment

    Working...
    X