Wednesday, November 28, 2012

Decode a mongo BinData field into a Guid with C#

This C# snippet will decode a mongo BinData field into a Guid

got this from Mongo:
{
  "_id" : ObjectId("50b40a5db14ea8902cd5d5ed"),
   "MyGuid : new BinData(3, "MC/0P9nkEeGgjYQrK2V3pQ=="),

   ...
}

but want to know the value of MyGid?  Try this little snippet:

using System;
namespace MongoGuidDecoder
{
    class Program
    {
        static void Main(string[] args)
        {
            var input = args[0];
            var bytes = Convert.FromBase64String(input.Trim());
            var guid = new Guid(bytes);
            Console.WriteLine(input);
            Console.WriteLine(guid);
        }
    }
}


Now run to get the Guid representation:
>MongoGuidDecoder MC/0P9nkEeGgjYQrK2V3pQ==
MC/0P9nkEeGgjYQrK2V3pQ==
3ff42f30-e4d9-e111-a08d-842b2b6577a5

No comments:

Post a Comment