Query with conditions using Mongodb Irrigation + nodejs

Asked

Viewed 684 times

-1

I have a code that returns me arrays with the parameters I need to feed my HTML page, however, I need to include some conditions in this search so that it only takes the values after a certain date.

var obj = await Hist.aggregate([{$group: {
        _id:'$pagform', 
        contagem:{$sum:1}, 
        soma:{$sum:'$valor'}
    }}])
    labels = []
    contagem = []
    soma=[]
    obj.forEach(x => {
        labels.push(x._id),
        contagem.push(x.contagem)
        soma.push(x.soma)
    });
    res.json({labels, contagem, soma})

It would be code similar to find(), but return me a json with the same arrays as the query using Aggregate, for example:

var all = await Hist.find({hora_saida:{ $gt: '2020-02-01' }},{'pagform':1,'valor':1,'':1})

1 answer

0


Understand how the pipelines of aggregate?

Basically you are passing an array of commands to be executed in your database, the return of each command, is passed as input to the next.

In the if code you have the following:

Hist.aggregate([
  {
    $group: {
      _id: '$pagform', 
      contagem: { $sum: 1 }, 
      soma: { $sum: '$valor' }
    }
  }
])

In this code there is only one command, $group, it will be executed on all documents of your Collection Hist. If you want it only run on the documents whose hora_saida is greater than 2020-02-01, you can add a command to filter these documents before running the $group:

Hist.aggregate([
  { 
    $match: { 
      hora_saida: { $gt: '2020-02-01' }
    } 
  },
  {
    $group: {
      _id: '$pagform', 
      contagem: { $sum: 1 }, 
      soma: { $sum: '$valor' }
    }
  }
])

The return of $match shall be the documents of the specified date, these documents shall serve as input to the $group.


In note: the query I used as an example would only work if your hora_saida be safe with the guy string, what is probably wrong. If hora_saida be the type Date, you should use hora_saida: { $gt: new Date('2020-02-01') }

  • Very good your answer, helped too, thank you!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.