Selim Mıdıkoğlu
Selim Mıdıkoğlu

Reputation: 136

How to aggregate data which an array field sum is between two values?

I have two values which are minCount and maxCount.

In my model I have field which is called counts.Something like this.

{
   createdAt: date 
   counts: [ 0,200,100] ==> Sum 300
},
{
    createdAt: date 
    counts: [ 200,500,0] ==> Sum 700
},
{
    createdAt: date 
    counts: [ 0,1100,100] ==> Sum 1200
},

I need to return sum of counts which sum of counts array elements are between minCount and MaxCount.

Exm:

minCount= 400
maxCount= 1300

Return

{
    createdAt: date 
    total: 700
},
{
    createdAt: date 
    total: 1200
},

I

I have createdAt dates between two dates like this in first step of pipe.

Record.aggregate ([
{
  $match: {
    createdAt: {
      $gte: new Date (req.body.startDate),
      $lte: new Date (req.body.endDate),
    },
  },
},
{}, ==> I have to get total counts with condition which I could not here. 

])

I am almost new to aggreagate pipeline so please help.

Upvotes: 0

Views: 222

Answers (1)

Rajat Goel
Rajat Goel

Reputation: 2305

Working example - https://mongoplayground.net/p/I6LOLhTA-yA

db.collection.aggregate([
  {
    "$project": {
      "counts": 1,
      "createdAt": 1,
      "totalCounts": {
        "$sum": "$counts"
      }
    }
  },
  {
    "$match": {
      "totalCounts": {
        "$gte": 400,
        "$lte": 1300
      }
    }
  }
])

Upvotes: 1

Related Questions