0

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

Community
  • 1
  • 1
user1895915
  • 89
  • 2
  • 11
  • Possible duplicate of [Mongodb concat int and string](https://stackoverflow.com/questions/33891511/mongodb-concat-int-and-string) – Dane411 Jul 01 '17 at 07:57

2 Answers2

1

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]
            }
        ]
    }
 }
s7vr
  • 73,656
  • 11
  • 106
  • 127
0

Conversion of int to str will not be possible in the pipeline. So $concat wont be possible on for the given data format.

Another method which could work would be trick to convert the year, month, day into a BSON Date format object.

The inspiration is that 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. This will be tedious, but hopefully you get the idea.

For the dateObj to a string part use $dateToString

Community
  • 1
  • 1
hyades
  • 3,110
  • 1
  • 17
  • 36