简体   繁体   中英

Java Mongo DB aggregation pipeline - $sum will not work while using $unwind?

I am currently working on a mongoDB aggregation pipeline in one of my Java scripts.

The input data can be simplified to a list of orders of different customers. Such as:

_id customerId orderId shipments amount
1 123 a12b4 shipment1, shipment2 30.00
2 456 a14hf shipment3 40.00
2 123 a27jd shipment4 20.00

_id, customerId, and orderId are strings, the amount a number of type Long, and the shipments are entities of a custom-made class called shipment. Now, I want to aggregate this and show, for every customerId, the total amount of what they spent and all the shipments. Like this for the first customer:

{customerId: 123, shipments: [shipment1, shipment2, shipment4], amount: 50.00}

Data in json format

[
 {
   "_id": 1,
   "customerId": 123,
   "orderId": "a12b4",
   "shipments": ["shipment1","shipment2"],
   "amount": 30
 },
 {
   "_id": 2,
   "customerId": 456,
   "orderId": "a14hf",
   "shipments": ["shipment3"],
   "amount": 40
 },
 {
   "_id": 3,
   "customerId": 123,
   "orderId": "a27jd",
   "shipments": ["shipment4"],
   "amount": 20
 }
]

So, I did this:

Aggregates.unwind("$shipments"),
Aggregates.group("$customerId",
     Accumulators.sum("amount","$amount"),
     Accumulators.addToSet("shipments", "$shipments")),
Aggregates.out("test_output")

And this is where my question comes in: Are the usages of unwind and sum exclusive?

As long as I keep my unwind statement, the sum function does not return the correct result. But it works just fine as soon as I replace shipments by another field that I do not have to unwind.

Any hints would be greatly appreciated.

Query

  • unwind will create many duplicated but you dont need it
  • you can group and sum, and collect the shipments for each customer
  • and then reduce to flatten the array, and union with [] to make it set (not duplicate shipments)

Playmongo

aggregate(
[{"$group": 
   {"_id": "$customerId",
    "shipments": {"$push": "$shipments"},
    "total-amound": {"$sum": "$amount"}}},
 {"$set": 
   {"shipments": 
     {"$setUnion": 
       [{"$reduce": 
           {"input": "$shipments",
            "initialValue": [],
            "in": {"$concatArrays": ["$$value", "$$this"]}}}, []]}}}])

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM