如何聚合数组值之和在两个值之间的数据?

时间:2019-08-27 10:43:43

标签: mongodb mongoose

我有两个值,分别是minCount和maxCount。

在我的模型中,我有一个称为计数的字段。类似这样的东西。

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

我需要返回计数总和,该计数总和数组元素在minCount和MaxCount之间。

Exm:

minCount= 400
maxCount= 1300

返回

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

在管道的第一步中,我已经在两个日期之间创建了atAt日期。

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. 

])

我几乎不熟悉管道,请帮忙。

1 个答案:

答案 0 :(得分:1)

工作示例-https://mongoplayground.net/p/I6LOLhTA-yA

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