-1

I was wondering if there is a way to "flatten" though projection a nested sub-document array so I could use it to sum its entries based on type.

My document looks like this:

{
      "order_id":12345,
      "date":8/17/2019,
      "payment":{
        status:1,
        transactions:[
          {type: 1, amount:200},
          {type: 2, amount:250},
          {type: 3, amount:50},
          {type: 4, amount:50},
        ]
      }
    }
    
    I would like to see if you can "flatten" it to something like this using $project:
    {
      "order_id":12345,
      "date":8/17/2019,
      "status":1,
      "type": 1, 
      "amount":200
     },
     {
      "order_id":12345,
      "date":8/17/2019,
      "status":1,
      "type": 2, 
      "amount":250
     },
     {
      "order_id":12345,
      "date":8/17/2019,
      "status":1,
      "type": 4, 
      "amount":50
     },
     {
      "order_id":12345,
      "date":8/17/2019,
      "status":1,
      "type": 4, 
      "amount":50
     }
      
    }
    
  

Primarily my goal is to aggregate all the amounts for transactions of type 1 & 3 and all the transactions with type 2 & 4.

Any help would be great.
Or A
  • 1,789
  • 5
  • 29
  • 55

1 Answers1

1

The following query can get you the expected output:

db.check.aggregate([
    {
        $unwind:"$payment.transactions"
    },
    {
        $project:{
            "_id":0,
            "order_id":1,
            "date":1,
            "status":"$payment.status",
            "type":"$payment.transactions.type",
            "amount":"$payment.transactions.amount"
        }
    }
]).pretty()    

Output:

{
    "order_id" : 12345,
    "date" : "8/17/2019",
    "status" : 1,
    "type" : 1,
    "amount" : 200
}
{
    "order_id" : 12345,
    "date" : "8/17/2019",
    "status" : 1,
    "type" : 2,
    "amount" : 250
}
{
    "order_id" : 12345,
    "date" : "8/17/2019",
    "status" : 1,
    "type" : 3,
    "amount" : 50
}
{
    "order_id" : 12345,
    "date" : "8/17/2019",
    "status" : 1,
    "type" : 4,
    "amount" : 50
}
Himanshu Sharma
  • 2,940
  • 1
  • 7
  • 18