[英]MongoDB $concatenate Date Error
I am working on a mongo aggregation project to group average readings every two hours which returns the desired output as follows 我正在进行一个mongo汇总项目,以便每两个小时对平均读数进行分组,以返回所需的输出,如下所示
{
"_id": {
"Year": 2016,
"locationID": " WL 001",
"Day": 25,
"Hour": 12,
"Month": 1
},
"temperature": 10.858749999999999,
"pH": 0,
"Conductivity": 2032.375
}
I want to regroup the data format and concatenate the date portion of the _id field so that it represent a new data format format below 我想重新组合数据格式并连接_id字段的日期部分,以便它代表下面的新数据格式
{
"_id": {
"locationID": " WL 001",
},
"Readings": {
"temperatue": {
"value": 8.879
},
"SensoreDate": {
"value": "2016-01-25:12"
},
"pH": {
"value": 16.81
},
"Conductivity": {
"value": 1084
}
},
}
Here is the $project portion of my aggregation query 这是我的聚合查询的$ 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"]} }
}
}
}
but i am getting an error $concat only supports strings, not NumberInt32 I have tried several options but can not get it to work 但我遇到一个错误$ concat仅支持字符串,不支持NumberInt32我尝试了几种方法但无法正常工作
Conversion of int to str will not be possible in the pipeline. 在管道中无法将int转换为str。 So $concat
wont be possible on for the given data format. 因此,对于给定的数据格式, $concat
是不可能的。
Another method which could work would be trick to convert the year, month, day into a BSON Date
format object. 另一种可行的方法是将年,月,日转换为BSON Date
格式对象的技巧 。
The inspiration is that dateObj: {$add: [new Date(0), '$time_in_sec_epoch']}
. 灵感来自dateObj: {$add: [new Date(0), '$time_in_sec_epoch']}
。
The calculation of $time_in_sec_epoch
can be done using aggregation operators like $sum
, $divide
, $subtract
etc. You can use the formula as given in this answer . $time_in_sec_epoch
的计算可以使用聚合运算符(例如$sum
, $divide
, $subtract
等)完成。您可以使用此答案中给出的公式。 This will be tedious, but hopefully you get the idea. 这将很乏味,但希望您能理解。
For the dateObj
to a string part use $dateToString
对于dateObj
到字符串部分,请使用$dateToString
You may use concat with substr to join them into a date. 您可以将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]
}
]
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.