title: Performance improvement for mongo count query
body: <p>The <code>mongoTemplate.count(new Query(), getCollectionName())</code> API eventually runs an aggregation and it sometime takes more than 3 minutes to run form mongod logs.</p>
  <p>Code : <a href="https://www.codota.com/web/assistant/code/rs/5c65df051095a5000188be30#L218" rel="nofollow noreferrer">https://www.codota.com/web/assistant/code/rs/5c65df051095a5000188be30#L218</a></p>
  <pre><code>[{
          $match: {}
      }, {
          $group: {
              _id: 1,
              n: {
                  $sum: 1
              }
          }
      }
  ]
  </code></pre>
  <p>The collection on which the count is ran can have too many writes(insert, delete) and reads (count, read documents from collection) in parallel from multiple nodes/threads. That could be the reason for the slowness.</p>
  <p>As a fix, I am planning to use the <code>estimatedDocumentCount</code> API</p>
  <pre><code>mongoTemplate.getCollection(getCollectionName()).estimatedDocumentCount()
  </code></pre>
  <p>But I am worried that the estimatedDocumentCount might not be accurate all the time, and that can add some drawbacks to the system.</p>
  <p>Another option is to use <code>find</code> API by projecting only &quot;_id&quot; fields and then get the size of the list.</p>
  <pre><code>Query query = new Query();
  query.fields().include(&quot;_id&quot;);
  mongoTemplate.find(query, getConcreteClass(), getCollectionName()).size()
  </code></pre>
  <p>But, the collection can sometimes have more than a million records. Every customer has a separate tenant databases and all of them can have 0 to 2M records in their database. If we use the above find query approach, there might be a scenario that multiple customers data are loaded at the same time and that might cause an OutOfMemoryError in java.</p>
  <p>Is there any other approach to solve this problem?</p>