How to use index in $match aggregation

let logs = await Promise.all( (item) => {
        for (let index = 0; index <= item.length; index++) {
          return await this.logModel.aggregate([
            //find({ terminalId: item }).model.
            { $match: { terminalId: item[index] } },
              $group: {
                _id: '$outcome',
                value: {
                  $sum: 1,
              $project: {
                name: '$_id',
                value: 1,
                _id: 0,
    console.log('logs', logs);
    return logs.flat();

I want to match data with specific Id each time
NB: item = [‘id1’,‘id2’]
I just got the first iteration means it matchs the id1 and it stops any solution or alternative to have loop through the array and get all matchs ?
I know that I can use find() method but i need the aggregation to make group by and sum after the opertation

You get only the first one because you call return.

How can I fix it please ??

If you want to process all the elements of your array with your for loop do not call return inside your for loop.

See return - JavaScript | MDN

$match uses the same syntax as find so I’m a bit confused by your comment that you can use find for this but want to use aggregation.

Can you explain exactly what documents you want to match (and then group)? It’s not really clear to me from this code.


I want to use aggregation for reason to use $group, find() doesn’t allows me to use $group
Solution : In case any one wants to match item in array just use $in

            $match: {
              terminalId: { $in: item },

My fault was the $match once find the matched data will stop automatically but i want to match all item in the array , so mongoose offer to us $in that alows us to match every item in array and stops when it matchs all data in array :stuck_out_tongue: :smiley:

1 Like

Actually that’s a standard MongoDB query operator, nothing mongoose specific.

Glad you were able to work it out.


1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.