Monday 5 June 2017

Mongodb aggregation pipeline nodejs: $unwind and $aggregate unique array elements

I have a following collection:

     transactions: {
         service1: [{ amount: 10, reference:'aaa', date: "today"},
           { amount: 100, reference: 'bbb' date: "somedate"},
           { amount: 10, reference: 'eee' date: "today"}
          ]
         service2: [{ amount: 30, reference: 'ccc' date: "today"},
          { amount: 40, reference: 'ddd' date: "today"},
          { amount: 10, reference: 'aaa' date: "today"},
          { amount: 10, reference: 'blah' date: "somedate"},
          ]
    }

I want to know the total amount of unique transactions (unique reference number) that are processed today. So my query should get total of only these transactions from above collections and no duplicate transaction.

{ amount: 10, reference:'aaa', date: "today"},
{ amount: 10, reference: 'eee' date: "today"},
{ amount: 30, reference: 'ccc' date: "today"},
{ amount: 40, reference: 'ddd' date: "today"},

so output would be: {amount: 90, count: 4}

I have tried to write the aggregation pipeline but it is not giving me the results I want, I can't seem to get unique records from two arrays and then aggregate them. Any help will be highly appreciated.



via Rani

No comments:

Post a Comment