I need to count the size of an array object and I also need to get the averages for each field in the array labeled raised_amount. However, MongoDB will not let me count the array size after unwinding it(duh). Mongo will not let me count the array size before unwinding either. This is for a class I am taking. Quite the challenge.
db.research.aggregate({$unwind:"$funding_rounds"},
{"$group": {
"_id":{"name": "$name"},
"averageFunding" : {
"$avg" : "$funding_rounds.raised_amount"
}
}
},
{$project: { count: { $size:"$funding_rounds" }}},
{ $sort: { averageFunding: -1 } },
{"$limit":10})
Take out {$project: { count: { $size:"$funding_rounds" }}} and it works! However, I wouldn't have funding_round count. Try to count the rounds by themselves, and it works.
Example of data:
{
"name": "Facebook",
"total_money_raised": "$39.8M",
"funding_round": [
{
"example": 123,
"round_code": "a",
"raised_amount": "1232"
},
{
"example": 123,
"round_code": "bat",
"raised_amount": "1232"
},
{
"example": 123,
"round_code": "cat",
"raised_amount": "1232"
}
]
}
Any ideas on how to count the array size in this aggregation?