Search code examples
mongodbuuid

MongoDb, Convert UUID to string, in projection


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


Solution

  • @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