'using $match + $sum condition in mongo Aggregation

I have an application running on graphql that queries some data in mongodb.

Within the resolver we have some filtering conditions using where :

export default {
  Query: {
  analytics: async (_, args, { me }) => {
  // here is the filters taken by args
  const {
    offset = 0, limit = 100, cnpj = '',
    finality = '', source = '', status = '', type = '',
    destinataryCity = '', emitterCity = '', emitter = '',
    accountId = '', startDate = '', endDate = ''
  } = args
  const client = new 
  MongoClient(process.env.MONGODB_CONNECTION_STRING)
  await client.connect()

  const odinDB = client.db('odin')
  const companyDB = client.db('companyServiceDB')
  const analytics = odinDB.collection('nfe_analytics')
  const companies = companyDB.collection('company')

  let where = {}

  if (finality) {
    where = { ...where, finality: finality }
  }
  if (source) {
    where = { ...where, source: source }
  }
  if (status) {
    where = { ...where, status: status }
  }
  .
  .
  .
  // here is the where condition enter in the query
  let rows = await analytics.find(where).sort({ date: -1 }).skip(offset).limit(limit).toArray()

and I have some field filters, such as CNPJ, data, source, etc

When I filter by the cnpj field, i do a sum of 2 fields using the aggregation:

  let amount = 0
  let total = 0
  const pipeline = [
    {
      $match: {
        destinatary: cnpj
      }
    }, {
      $group: {
        _id: '$destinatary',
        amount: {
          $sum: '$amount'
        },
        total: {
          $sum: '$value'
        }
      }
    }
  ]
  if (cnpj) {
    where = { ...where, destinatary: { $regex: cnpj } }
    const [results] = await analytics.aggregate(pipeline).toArray()
    amount = results.amount
    total = results.total
  }

but when I use the combined filter, for example, cnpj + ordernumber, the sum field appears with the value as if it were adding without the filter

using combined filter, we get the same sum value

I would like the sum to work for any filter combination, is it possible?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source