gpt4 book ai didi

java - MongoDB - 使用 Java 添加嵌套数组

转载 作者:行者123 更新时间:2023-11-30 06:40:13 25 4
gpt4 key购买 nike

我正在尝试使用 Java 在“simulatedProducts”数组内添加一个“discountList”数组来填充 MongoDB 集合。但是,它们是单独添加的,我不确定如何编写此代码,以便将discountList填充到simulatedProducts中。

有人可以帮我解决这个问题吗?

这是代码(每个都在 a 内):

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);
}

添加到集合中的返回结果:

{
"simulatedProduct": [{
"name": "X",
"minimum": 1000
}, {
"name": "Test",
"minimum": 2380
}, "discountList": [{
"nameDiscount": "Tax",
"percentage": 3
}, {
"nameDiscount": "Something",
"percentage": 3
}]
}
}

预期结果:

{
"simulatedProduct": [{
"name": "X",
"minimum": 1000,
"discountList": [{
"nameDiscount": "Tax",
"percentage": 3
}, {
"nameDiscount": "Something",
"percentage": 3
}]
}, {
"name": "Test",
"minimum": 2380
}, "discountList"
}
}

最佳答案

您可以重构代码。

下面的代码将一次迭代一个产品,创建一个更新文档,设置nameminimum并推送discountList并添加将文档更新到 productList

您可以使用 productList 运行更新查询来推送整个 simulatedProduct 数组。

类似于

 BasicDBList productList = new BasicDBList();
for (Product produto : wallet.getSimulation().getFutureProductList()) {
BasicDBList discountList = new BasicDBList();
for (Discount discount : produto.getDiscountList()) {
discountList.add(new BasicDBObject("nameDiscount", discount.getNameDiscount()).append("percentage", discount.getPercentage()));
}
productList.add(new BasicDBObject("name", produto.getName()).append("minimum", produto.getMinimun()).append("discountList", discountList));
}
DBObject update = new BasicDBObject("$push", new BasicDBObject("simulatedProduct", productList));
collection.update(document, update, true,true);

关于java - MongoDB - 使用 Java 添加嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44478275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com