AlexZeDim
AlexZeDim

Reputation: 4352

MongoDB: concatinate multiple number values to string

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.

Upvotes: 6

Views: 1424

Answers (1)

turivishal
turivishal

Reputation: 36114

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

Upvotes: 9

Related Questions