0

I am getting below documents after my $project , but now I need to find out the average of the transactions. Below are the documents after my '$project', before '$group'

{ "name" : "AAA", "transactions" : [ { "amount" : 500000 }, { "amount" : 12700000 }, { "amount" : 27500000 } ] } { "name" : "BBBB", "transactions" : [ { "amount" : 2500000 }, { "amount" : 5500000 }, { "amount" : 18000000 } ] } { "name" : "CCCC", "transactions" : [ { "amount" : 10000000 }, { "amount" : 5000000 }, { "amount" : 1000000 } ] } 

I tried something like this.

 {$group:{"_id":"$name", average:{$avg:"$transactions.amount"}}} 

I am printing name values in _id field but the 'average' is printing 'null'

here is the output I am getting

{ "_id" : "AAA", "average" : null } { "_id" : "BBB", "average" : null } { "_id" : "CCC", "average" : null } 

what am I missing?

1 Answer 1

2

The problem with you $group stage on the aggregation framework, is that there is nothing to sum up to make an average. I mean, you are working around the "pure" array of values, but the $avg expression is not intelligent enough to sum up all the content of the array. You are trying to get an average of the array as a whole. The correct way to achieve this is doing an $unwind on a previous stage so you got documents like this

{ "name" : "AAA", "transactions" : {"amount" : 500000} } { "name" : "AAA", "transactions" : {"amount" : 12700000} } { "name" : "AAA", "transactions" : {"amount" : 27500000} } 

now, you can do your $group stage that should look like

{$group:{"_id":"$name", average:{$avg:"$transactions.amount"}}} 

this will make an average for each element contained in the transactions array that you $unwind before to have a document for each of the member.

I think you are taking a mongodb course on mongo university, good luck!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.