如何按字段A对其区域B进行递增计数

时间:2019-01-23 13:40:06

标签: mongodb mongoose

我想使用猫鼬对下面的数据进行mongodb查询。

这是有关某些商店的客户评分日志。

[
  {
    "store": "starbucks",
    "rating": "3",
    "birthday": "1990-01-01"
  },
  {
    "store": "starbucks",
    "rating": "4",
    "birthday": "1985-01-01"
  },
  {
    "store": "starbucks",
    "rating": "5",
    "birthday": "1960-01-01"
  },
  {
    "store": "mcdonalds",
    "rating": "5",
    "birthday": "1995-01-01"
  },
  {
    "store": "mcdonalds",
    "rating": "3",
    "birthday": "1982-01-01"
  },
  {
    "store": "mcdonalds",
    "rating": "2",
    "birthday": "1970-01-01"
  }
]

按年龄段分组存储和计算评分。

例如,

[
  {
    "store": "starbucks",
    "26-35": 2, // Two peoples rated starbucks between 26 and 35 years old
    "36-45": 1
  },
  {
    "store": "mcdonalds",
    "26-35": 2,
    "36-45": 1
  }
]

我应该使用什么?聚集还是分组?

1 个答案:

答案 0 :(得分:0)

这是shell脚本:

db.getCollection('CUSTOMER').aggregate(
   [
      {
        $group : { _id: "$store", 
        LessThen35 : { $sum: {$cond: [ { $lt: [ 
                               { $abs: {$subtract: [ 
                                       {$dateFromString: { dateString: '$birthday'}},
                                        new Date()
                                        ]}
                                    }
            , 35*356*24*60*60*1000 ] }, 1, 0 ]}},
        GreEqu35 : { $sum: {$cond: [ { $gte: [ 
                          { $abs: {$subtract: [ 
                                      {$dateFromString: { dateString: '$birthday'}},
                                        new Date()
                                        ]}
                                    }
            , 35*356*24*60*60*1000 ] }, 1, 0 ]}},


        }
  }
  ])

这是结果

/* 1 */
{
    "_id" : "mcdonalds",
    "LessThen35" : 1.0,
    "GreEqu35" : 2.0
}

/* 2 */
{
    "_id" : "starbucks",
    "LessThen35" : 2.0,
    "GreEqu35" : 1.0
}