MongoDB $concatenate 日期错误

MongoDB $concatenate Date Error

我正在研究一个 mongo 聚合项目,以每两个小时对平均读数进行分组,returns 所需的输出如下

{
        "_id": {
            "Year": 2016,
            "locationID": " WL 001",
            "Day": 25,
            "Hour": 12,
            "Month": 1
        },
        "temperature": 10.858749999999999,
        "pH": 0,
        "Conductivity": 2032.375
    }

我想重新组合数据格式并连接 _id 字段的日期部分,以便它代表下面的新数据格式格式

{
    "_id": {
       "locationID": " WL 001",
    },
    "Readings": {
        "temperatue": {
            "value": 8.879
        },
        "SensoreDate": {
            "value": "2016-01-25:12"
        },
        "pH": {
            "value": 16.81
        },
        "Conductivity": {
            "value": 1084
        }
    },
}

这是我的聚合查询的 $project 部分

{
    "$project": {
        '_id': '$_id.locationID',
        'Readings': {
            'pH': {'value': '$pH'},
            'temperature': {'value': '$temperature'},
            'Conductivity': {'value': '$Conductivity'},
            'SensoreDate': {'value': {'$concat': ["$_id.Year", "$_id.Month", "$_id.Day", "$_id.Hour"]} }
        }
    }
}

但是我得到一个错误$concat 只支持字符串,不支持 NumberInt32我已经尝试了几个选项但无法让它工作

管道中无法将 int 转换为 str。所以 $concat 对于给定的数据格式是不可能的。

另一种可行的方法是 trick 将年、月、日转换为 BSON Date 格式对象。

灵感是dateObj: {$add: [new Date(0), '$time_in_sec_epoch']}.

$time_in_sec_epoch 的计算可以使用 $sum$divide$subtract 等聚合运算符来完成。您可以使用此 [= 中给出的公式19=]。这将是乏味的,但希望你明白了。

对于 dateObj 到字符串部分使用 $dateToString

您可以使用 concat 和 substr 将它们连接成一个日期。

'SensoreDate': {
    'value': {
        '$concat': [{
                $substr: ["$_id.Year", 0, -1]
            },
            "-", {
                $substr: ["$_id.Month", 0, -1]
            },
            "-", {
                $substr: ["$_id.Day", 0, -1]
            },
            ":", {
                $substr: ["$_id.Hour", 0, -1]
            }
        ]
    }
 }