Count the elements in a arrays in Mongodb documents: efficiency and performance
<p>I have a collection in a mongodb.  The documents contain an array.  I want to know how many element exist in all arrays in all documents.  There are a couple of ways of doing this (covered in this question: <a href="https://stackoverflow.com/questions/21387969/mongodb-count-the-number-of-items-in-an-array">MongoDB: count the number of items in an array</a>), and I want to know which method is more efficient, and how to tell which method is more efficient.</p>

<p>The documents look like this:</p>

<pre><code>{"foo":[1,2,3,4]}
{"foo":[5,6,7]}
</code></pre>

<p>I can get the number I want by running either:</p>

<pre><code>db.countTest.aggregate([{$unwind:"$foo"},{$group:{_id:null,"total foo":{$sum:1}}}])
</code></pre>

<p>or</p>

<pre><code>db.countTest.aggregate([{$project:{count:{$size:"$foo"}}},{$group:{_id:null,"total foo":{$sum:"$count"}}}])
</code></pre>

<p>SO my question is: which method is more efficient, and how do i tell which is more efficient.  I have run the aggregate queries with {explain:true} however I didn't find anything especially useful in the output.  My feeling is the second method is more efficient, since it doesn't require the unwind, but I was hoping to be able to prove that.  The reason for asking is that this example is a scaled down version of a real life scenario with much more, much larger documents.</p>

<p>Also, what are the potential performance impact of running these aggregations on the mongodb?  Could the aggregation affect the database performance in general, and the response times of other users?</p>

<p>thanks for your help.</p>