I am new to MongoDB. After a lot of searches, I have applied an aggregate operation as below and it's working as expected:
AggregateIterable<Document> summary= collection.aggregate(
Arrays.asList(
Aggregates.match(Filters.eq("financialEventType", "REFUND")),
Aggregates.group("_id",
Accumulators.sum("revenueHeader_Principal","$revenueHeader.Principal"),
Accumulators.sum("revenueHeader_ProductTax","$revenueHeader.Product Tax"),
Accumulators.sum("revenueHeader_Shipping","$revenueHeader.Shipping"),
Accumulators.sum("revenueHeader_ShippingTax","$revenueHeader.Shipping Tax"),
Accumulators.sum("revenueHeader_GiftWrap","$revenueHeader.Gift Wrap"),
Accumulators.sum("revenueHeader_GiftWrapTax","$revenueHeader.Gift Wrap Tax"),)
));
LinkedHashMap<String, BigDecimal> revenueSummary = new LinkedHashMap<String, BigDecimal>();
Now I want to save these values in revenueSummary in a specific order. But how do I iterate over summary or access the items by their name?
You may iterate with the while
statement.
Note: If there are more than 1 results, you will save the last document values.
MongoCursor<Document> iterator = summary.iterator();
while (iterator.hasNext()) {
Document next = iterator.next();
//Copy from Document key-value
revenueSummary.put("Principal", (BigDecimal) next.get("revenueHeader_Principal"));
revenueSummary.put("ProductTax", (BigDecimal) next.get("revenueHeader_ProductTax"));
//...
}
LINK: https://www.programcreek.com/java-api-examples/index.php?api=com.mongodb.client.AggregateIterable
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.