5

I have a document (inside aggregation, after $group stage) which have an object (but I could form array, if I needed it to) with number values.

MongoPlayground example with data and my aggregate query available here.

And I want to make a new _id field during next $project stage, consisted of this three number values, like:

   item_id | unix time | pointer
_id: 453435-41464556645@1829

The problem is, that when I am trying to use $concat, the query returns me an error like:

$concat only supports strings, not int

So here is my question: is it possible to achieve such results? I have seen the relevant question MongoDB concatenate strings from two fields into a third field, but it didn't cover my case.

AlexZeDim
  • 3,520
  • 2
  • 28
  • 64
  • 1
    You `$concat` only support string, you need to convert your fields value to string using `$toString` check https://mongoplayground.net/p/SSlXW4gIs_X – turivishal Aug 03 '20 at 17:41
  • 1
    @turivishal that is great, thank you so much! Could you form it as an answer? So I can accept it and mark as solved? – AlexZeDim Aug 03 '20 at 17:50

1 Answers1

8

The $concat only concatenate strings, these fields $_id.item_id contains int value and $_id.last_modified double value,

The $toString converts a value to a string,

_id: {
  $concat: [
    {
      $toString: "$_id.item_id"
    },
    " - ",
    {
      $toString: "$_id.last_modified"
    }
  ]
}

Playground: https://mongoplayground.net/p/SSlXW4gIs_X

turivishal
  • 34,368
  • 7
  • 36
  • 59