MongoDb BinData to Guid (UUID) options (shell, PowerShell & GUI tools: MongoVue, RoboMongo)
While double checking some new features we have been working on we had to track some documents and make sure they update correctly when we send and receive messages. The id’s where Guids stored as bindata (binary data).
#Note: Guid (C#) is just Microsofts implementation of UUID (Universally Unique Identifier)- and is basically the same.
Here is an example of BinData from a document when we retrieved with MongoVue
“CustomerEnquiryId” : new BinData(3, “+e280Lr9rEiIFsWKNbrzFQ==”)
If you just quickly want to convert that to a .Net Guid, and you are not using a GUI tool you could simply use this little PowerShell function I wrote:
$uuid = “+e280Lr9rEiIFsWKNbrzFQ=="
Function Get-Guid
{
Param(
[string]$uuid,
)
if(-not($uuid)) { Throw “You must supply binary or binaries” }
$uuid = new-object -TypeName System.Guid -ArgumentList (,[System.Convert]::FromBase64String($uuid))
return $uuid
}
Thank you Damirofor cleaning up my lazy script :))
$uuid = “+e280Lr9rEiIFsWKNbrzFQ==”
Function Convert-UUIDToGUID
{
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)] #with this you wont need to validate using an IF :)
[string[]]$uuid
)
foreach ($u in $uuid){
$Guid = new-object -TypeName System.Guid -ArgumentList (,[System.Convert]::FromBase64String($uuid))
return $Guid
}
}
Robin also has some scripts, check them out.
But, that might get tedious, so let’s have a look at a few more options. For some reason we encountered all of them at work as we hadn’t configured our environment tools correctly. Turns out that you need to enable the conversion in both MongoVue and RoboMongo- otherwise you will be presented with inaccurate data (in RoboMongo something that looks like .Net Guids but are not, and in MongoVue just the bindata value)
If we take a look at the document again:
new BinData(3, “+e280Lr9rEiIFsWKNbrzFQ==”)
Notice the ‘3’ ? This tells us the subtype, and 3 stands for UUID (old). The subtypes are explained in the bson specification.
From the BSON specififcation
Why do we need to know that? Because, some GUI tools for Mongo, such as RoboMongo support some of the subtypes. We first thought that something was a bit wack with the conversion, as the result wasn’t right in RoboMongo, - but turns out we had forgotten to enable Legacy UUID Encoding. Ops!
Of course, unless you are good at converting in your head (hah!) that string might not be very helpful. If you use RoboMongo I showed you above how to show the Guid correctly,- and if you use MongoVue then this setting might be of interest for you.
What if you don’t use GUI tool- or one that doesn’t support the convertion?
There is a JavaScript function, and a few steps, that you can use to convert, as described in StackOverflow question and answer.
In short you need this JS helper.
Comments
Last modified on 2014-09-19