title: Statistics with Mongo DB
body: <p>I have the following DB structure :</p>
  <pre><code>{
      &quot;uploadedAt&quot;: &quot;2021-09-22T22:09:12.133Z&quot;,
      &quot;paidAt: &quot;2021-09-30T22:09:12.133Z&quot;,
      &quot;amount&quot;: {
          &quot;currency&quot;: &quot;EUR&quot;,
          &quot;expected&quot;: 70253,
          &quot;paid&quot;: 0
      },
  }
  </code></pre>
  <p>I would like to know how do I calculate the total amount that still need to be paid (expected - paid), and the average date between uploadedAt and paidAt. This for multiple records.</p>
  <p>My function for getting the data is (the criteria should be updated to get this data).</p>
  <pre><code>const invoiceParams = new FindParams();
  invoiceParams.criteria = { company: company._id }
  
  const invoices = await this.findAll(invoiceParams);
  </code></pre>
  <p>FindAll function looks like:</p>
  <pre><code>  async findAll(
      params: FindParams,
      ability?: Ability,
      includeDeleted: boolean = false,
    ): Promise&lt;Entity[]&gt; {
      let queryCriteria: Criteria = params.criteria;
      let query: DocumentQuery&lt;Entity[], Entity&gt; = null;
  
      if (!includeDeleted) {
        queryCriteria = {
          ...queryCriteria,
          deleted: { $ne: true },
        };
      }
  
      try {
        if (ability) {
          ability.throwUnlessCan('read', this.entityModel.modelName);
  
          queryCriteria = {
            ...toMongoQuery(ability, this.entityModel.modelName),
            ...queryCriteria,
          };
        }
  
        query = this.entityModel.find(queryCriteria);
  
        if (params.populate) {
          query = query.populate(params.populate);
        }
  
        if (params.sort) {
          query = query.sort(params.sort);
        }
  
        if (params.select) {
          query = query.select(params.select);
        }
  
        return query.exec();
      } catch (error) {
        if (error instanceof ForbiddenError) {
          throw new ForbiddenException(error.message);
        }
  
        throw error;
      }
    }
  </code></pre>
  <p>Update:</p>
  <pre><code>const paymentTime = await this.invoiceModel.aggregate([
        {
            $group: {
                _id: &quot;$account&quot;,
                averageSpread: { $avg: { $subtract: [&quot;$paidAt&quot;, &quot;$uploadedAt&quot;] } },
                count: { $sum: 1 }
            }
        }
    ]);
  </code></pre>