mongodb,聚合嵌套字段哈希

时间:2019-07-19 06:58:03

标签: mongodb mongodb-query

我有一个集合,其中包含一些字段

gender: {male: 2, female: 1}, 
interest: {'game': 10, 'sport': 15, ...}

我想汇总一下:genders, interest

pipeline = [
  {'$project' => {
    "date": {
      "$dateToString":{
        date: '$timestamp',
        format: '%Y-%m-%d'
      }
    },
    "hour": {
      "$hour": "$timestamp"
    },
    "genders": "$genders"
  }},
  {'$group' => {
    "_id": {
      "date": "$date",
      "hour": "$hour"
    },
    'male': {'$sum' => '$genders.male'},
    'female': {'$sum' => '$genders.female'}
  }}
]

因为将来会有更多的键名添加到数据库中,所以查询中不应指定键名'male', 'female'.

您能指导我怎么做吗?

0 个答案:

没有答案