I have documents with an array field and I need to sum the sizes of this array across all documents. I'm using python --> PyMongo.
In a nutshell, applying the aforementioned query to this set of documents should return 6:
{_id: a, array: [a,b]}
{_id: b, array: [c, d, e]}
{_id: c, array: [f]}
Searching around the Internet, I've come up with the following solution:
value = collection.aggregate([{"$unwind": "$array"}, {"$group": {"_id": "null", "total": {"$sum": 1}}}])
It works and I get the number I want in the following way:
count = value['result'][0]['total']
Is it the best query I can do? Is there a more efficient way?
I'm not particularly expert about mongo aggregation framework, so I thought it was better to ask.