使用java更新mongodb中的数组

时间:2015-04-10 09:31:12

标签: java mongodb

{
    "_id" : 1,            
    "Accounts" : [ 
                {
                    "Date" : ISODate("2015-04-10T05:29:46.362Z"),
                    "Total_Debits" : 0,
                    "Total_Credits" : 0
                }
            ]
}




BasicDBObject search = new BasicDBObject();
search.put("_id", id);
search.put("Accounts.Date", date);
accounts.put("Total_Debits", total_Fp_Dr);
accounts.put("Total_Credits", total_Fp_Cr);
BasicDBObject update = new BasicDBObject();
update1put("$push", new  BasicDBObject("Accounts.$.Total_Debits",total_Fp_Dr));
                        accountHeads.update(search,update)

1 个答案:

答案 0 :(得分:0)

尝试重构您的查询,如下所示:

DBObject searchQuery = new BasicDBObject("_id", id).append("Date", date);
DBObject accountsArray = new BasicDBObject("Accounts", 
                             new BasicDBObject("Date", date)
                                .append("Total_Debits", total_Fp_Dr)
                                .append("Total_Credits", total_Fp_Cr));

DBObject updateQuery = new BasicDBObject("$push", accountsArray);
accountHeads.update(searchQuery, updateQuery);