【问题标题】:How to use Mongo aggregate in php to get counters?如何在php中使用Mongo聚合来获取计数器?
【发布时间】:2018-01-22 16:42:26
【问题描述】:

我正在尝试查询属性的集合以获取其不同值的计数器。我只按一个属性分组。无论集合中的数据类型如何,该请求都必须有效。

收藏

[
    {"name":"michel","bday":"1977-07-21"},
    {"name":"michel","bday":"1985-06-21"},
    {"name":"jean","bday":"1989-10-07"}
]

按生日分组输出

[
    {"1977" : 1},
    {"1985" : 1},
    {"1989" : 1}
] 

按名称分组输出

[
    {"michel" : 2},
    {"jean" : 1}
] 

我设法按名称分组,但如果我没有设法按日期分组。 对于日期,我可以决定按格式分组(月或年,...)

我有两个问题:

  • 如果我的日期是字符串,我不能使用 $dateToString。
  • 如果我的日期是 ISODate,该函数会返回一个对象“UTCDateTime,以毫秒为单位”,而不是日期格式。

我希望有一个管道来管理所有内容。

我目前的管道:

Array(
    [0] => Array(
            [$project] => Array(
                    [bday] => Array(
                            [$dateToString] => Array(
                                    [format] => %Y
                                    [date] => $bday
                                )
                        )
                )
        )
    [1] => Array(
            [$group] => Array(
                    [_id] => $bday
                    [count] => Array(
                            [$sum] => 1
                        )
                )
        )
)

只有当字段是日期时才可以应用 dateToString ?

【问题讨论】:

  • 不确定我是否关注你。你能添加预期的输出吗?您是否要分别按名称分组和按日期分组?您的日期字段是否同时包含字符串日期和 ISO 日期?请在帖子中添加要求的说明。

标签: php mongodb


【解决方案1】:

您可以使用$cond 运算符来检查带有$type 运算符的数据类型; if date type $dateToString else $substrCP$group 阶段获取年份。

类似

{"$group":{
  "_id":{
    "$cond":{
      "if":{"$eq":[{"$type":"$bday"},"date"]},
      "then":{"$dateToString":{"format":"%Y","date":"$bday"}},
      "else":{"$substrCP":["$bday",0,4]}
    }
  },
  "count":{"$sum":1}
}} 

【讨论】:

    【解决方案2】:

    感谢您的回复。 “$type”有一个错误。

    “无效的运算符'$type'”。

    我也试试:

    '$bday' => array('$type' => 'date')
    

    我使用 mongo 3.2.10。

    最后,我使用 $match 阶段来确定 $type。解决办法:

    {
        $match: {
            "bday": {
                "$type": "date"
            }
        }
    },
    {
        $group: {
            "_id": {
                "$dateToString": {
                    "format": "%Y",
                    "$bday"
                }
            },
            "count": {
                "$sum": 1
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-09-20
      • 1970-01-01
      • 2017-10-10
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多