Yaron Levi
Yaron Levi

Reputation: 13077

MongoDB C# - Differences of storing UUID as string vs binary?

I am using MongoDB along with the C# driver to store this entity:

public class Receipt
{
    [BsonId]
    public string Id { get; set; }
    //...
}

This Id is a UUID that is generated externally by mobile clients (android/iphone), and sent to the server as a string, like so:

"FD8E8599-9B63-404E-86E3-2EE1BA7F91E6"

Are there any differences regrading performance (read/write) or other usability issues compared to storing it as a binary:

public class Receipt
    {
        [BsonRepresentation(BsonType.Binary)]
        public byte[] Id { get; set; }
        //...
    }  

(The first method is preferred because i don't need to convert the incoming string to a byte array)

Upvotes: 2

Views: 4638

Answers (2)

David Gourde
David Gourde

Reputation: 3914

UUID (GUID) are implicitly converted by the C# Driver as BSON::Binary, as you can see in the documentation and we can see from the MongoDB doc that:

For a more efficient storage of the UUID values in the collection and in the _id index, store the UUID as a value of the BSON BinData type. Index keys that are of the BinData type are more efficiently stored in the index if: the binary subtype value is in the range of 0-7 or 128-135, and the length of the byte array is: 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, or 32.

Your UUID(GUID) is in that range, so the performance will be increased over the String representation (by a lot).

Upvotes: 0

salihk
salihk

Reputation: 65

Byte array will use 20 bytes for the storage (4 bytes for storing the length of the array, and 16 bytes to store your 128-bit uuid value).

The string version will use 41 bytes for the storage (4 bytes for storing the length, 36 bytes for storing the utf8 characters for the string representation of your uuid and 1 byte for storing the terminating null character i.e. \x00).

I would store it as a string because that would be easier to work with while querying the collection.

If you want to access your records quickly, you should define a single field index on your Id property.

See http://docs.mongodb.org/manual/core/index-single/ for detailed information.

Upvotes: 4

Related Questions