2

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.

1
  • 1
    Yes, This is the best way according to me. Commented Dec 8, 2014 at 19:58

1 Answer 1

2

No need to unwind the array just to get the size.

>>> collection.aggregate([{'$group': {'_id': None, 'total': {'$sum': {'$size': '$array'}}}}])
{u'ok': 1.0, u'result': [{u'total': 6, u'_id': None}]}
Sign up to request clarification or add additional context in comments.

1 Comment

It works! Is it also more efficient? I guess it is because it doesn't unwind.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.