I'm trying to add an array of "discountList" inside of an array of "simulatedProducts" using Java to populate a MongoDB collection. However, they are being added separetely, and I'm not sure how I can write this so that discountList is populated inside the simulatedProducts.
Can someone please help me with this?
This is the code (inside a for each):
DBCollection collection = database1.getCollection("wallet");
document.put("ID", id);
BasicDBObject document = new BasicDBObject();
collection.insert(document);
DBObject listItem = new BasicDBObject();
BasicDBObject pushOnProduct = new BasicDBObject();
for (Product produto : wallet.getSimulation().getFutureProductList()){
listItem = new BasicDBObject("simulatedProduct", new BasicDBObject
("name",produto.getName()).append("minimum",produto.getMinumum()).append[...]);
pushOnProduct.put("$push", listItem);
collection.update(document, pushOnProduct,true,true);
for(Discount discount: produto.getDiscountList()){
listItem = new BasicDBObject("discountList", new BasicDBObject
("nameDiscount",discount.getNameDiscount()).append("percentage",discount.getPercentage()));
pushOnProduct.put("$push", listItem);
collection.update(document, pushOnProduct,true,true);
}
Returned result that is added on the collection:
{
"simulatedProduct": [{
"name": "X",
"minimum": 1000
}, {
"name": "Test",
"minimum": 2380
}, "discountList": [{
"nameDiscount": "Tax",
"percentage": 3
}, {
"nameDiscount": "Something",
"percentage": 3
}]
}
}
Expected result:
{
"simulatedProduct": [{
"name": "X",
"minimum": 1000,
"discountList": [{
"nameDiscount": "Tax",
"percentage": 3
}, {
"nameDiscount": "Something",
"percentage": 3
}]
}, {
"name": "Test",
"minimum": 2380
}, "discountList"
}
}
documentfield ? Why not just do one update ?