6

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.

2
  • 1
    You $concat only support string, you need to convert your fields value to string using $toString check mongoplayground.net/p/SSlXW4gIs_X Commented Aug 3, 2020 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? Commented Aug 3, 2020 at 17:50

1 Answer 1

9

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.