I have below 3 sample records:
{
"_id" : "0cc5c468-2105-11ee-ad68-15d467e62by4d",
"storeId" : "3070",
"paymentType" : "cash",
"total" : {"$numberDecimal": "100"}
},
{
"_id" : "1111111-2105-11ee-ad68-15d467e62by4d",
"storeId" : "3070",
"paymentType" : "cash",
"total" : {"$numberDecimal": "100"}
},
{
"_id" : "0cc5c468-2105-11ee-ad68-15d467e62by4d",
"storeId" : "3070",
"paymentType" : "creditCard",
"total" : {"$numberDecimal": "50"}
}
I am trying to write some grouping and projection logic in which the desired output from above sample data should be as below:
StoreId | Cash Payment | Card Payment | Total Amount Cash + Card
3070 200 50 250
The last column can ofcourse be ignored but i need this kind of output from mongodb in java.
I have tried many things and below is the code I have so far which is not giving desired output, it gives me two separate records for card payment and cash payment types.
GroupOperation groupingLogic() {
return group("storeId", "paymentType")
.first("storeId").as("storeId")
.first("paymentType").as("paymentType")
.sum(TOTAL).as(TOTAL);
}
I am not sure how to get output as expected above with java mongodb code .
Please someone help.
2
Answers
Explanation:
storeId
+paymentType
) and sumpaymentType's
total amount.total amount
for allpaymentType
s for eachstoreId
.$arrayToObject
to pivot eachpaymentType
into field.Note:
cash
,creditCard
,check
, etc. are dynamically filled. If anystoreId
has no such payment types, these fields may not be there.Try this one:
MongoPlayground
Java – complex aggregation pipeline
If you want to group and add up some data from your MongoDB collection. Here’s how you can do it using Java with Spring Data MongoDB:
If You want to group the data by the "storeId" and sum the amounts for different payment types ("cash" and "creditCard"). Here’s how you can do that:
To show in your format. Here’s how you can do that:
Putting It All Together:
Remember to replace yourCollectionName with the actual name of your MongoDB collection and YourOutputType with the appropriate class that matches the expected output.