user1895915 user1895915 - 28 days ago 12
Python Question

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

{
"_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": {
"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": {
'_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

Answer

You may use concat with substr to join them into a date.

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