skip to Main Content

I’m looking for a solution to convert a UUID to a string using projection. I’ve tried many different ways, but none of them are working.

enter image description here

The stranger thing is that Metabase displays the ID correctly, but I cannot manipulate this data because it’s not in string format.

enter image description here
Have you any idea ?

Thanks a lot

Benjamin

2

Answers


  1. Chosen as BEST ANSWER

    @rickhg12hs

    Thank you a lot, your answer help me !

    But in my case my Id was BinData 3

    {
      "_id": BinData(3, "OyQRAeK7QlWMr0E2xWapYg==")
    }
    

    I refactor your answer as follow :

    db.collection.aggregate([
      {
        "$project": {
          "_idUUIDstr": {
            "$function": {
              "body": "function convert(s){let t=s.hex();var r=t.substr(6,2)+t.substr(4,2)+t.substr(2,2)+t.substr(0,2),u=t.substr(10,2)+t.substr(8,2),b=t.substr(14,2)+t.substr(12,2),e=t.substr(16,16);return t=r+u+b+e,t.substr(0,8)+'-'+t.substr(8,4)+'-'+t.substr(12,4)+'-'+t.substr(16,4)+'-'+t.substr(20,12)}",
              "args": [
                "$_id"
              ],
              "lang": "js"
            }
          }
        }
      }
    ])
    

    and is work perfectly

    RESULT

    [
      {
        "_id": BinData(3, "OyQRAeK7QlWMr0E2xWapYg=="),
        "_idUUIDstr": "0111243b-bbe2-5542-8caf-4136c566a962"
      }
    ]
    

    https://mongoplayground.net/p/qf7e5d2aA41


  2. I hope there is a better answer as I consider this very fragile since it depends on JavaScript execution being enabled on the MongoDB server and a fixed toString representation of BinData UUID. Until there is something better, perhaps this is good enough.

    db.collection.aggregate([
      {
        "$project": {
          "_idUUIDstr": {
            "$function": {
              "body": "function(x) {return x.toString().slice(6,-2)}",
              "args": ["$_id"],
              "lang": "js"
            }
          }
        }
      }
    ])
    

    Example document:

    {
      "_id": BinData(4, "OyQRAeK7QlWMr0E2xWapYg==")
    }
    

    Example output:

    {
      "_id": BinData(4, "OyQRAeK7QlWMr0E2xWapYg=="),
      "_idUUIDstr": "3b241101-e2bb-4255-8caf-4136c566a962"
    }
    

    Try it on mongoplayground.net.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search