-
Mar 6th, 2012, 12:46 AM
#1
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!
-
Mar 6th, 2012, 11:52 AM
#2
I think using "accounts[0].balance" instead of just "balance" should do the trick.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules