Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDb, Convert UUID to string, in projection

Tags:

uuid

mongodb

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

like image 213
btbenjamin Avatar asked Oct 21 '25 03:10

btbenjamin


1 Answers

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.

like image 114
rickhg12hs Avatar answered Oct 22 '25 16:10

rickhg12hs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!