17

An application persists Guid field in Mongo and it ends up being stored as BinData:

"_id" : new BinData(3, "WBAc3FDBDU+Zh/cBQFPc3Q==")

The advantage in this case is compactness, the disadvantage shows up when one needs to troubleshoot the application. Guids are passed via URLs, and constantly transforming them to BinData when going to Mongo console is a bit painful.

What are drawbacks of storing Guid as string in addition to increase in size? One advantage is ease of troubleshooting:

"_id" : "3c901cac-5b90-4a09-896c-00e4779a9199"

Here is a prototype of a persistent entity in C#:

class Thing
{
    [BsonIgnore]
    public Guid Id { get; set; }

    [BsonId]
    public string DontUseInAppMongoId
    {
        get { return Id.ToString(); }
        set { Id = Guid.Parse(value); }
    }
}
Yuriy Zubarev
  • 2,821
  • 18
  • 24
  • Memory, space and querying time and index size are some, what you can do to optimise is this: http://www.mongodb.org/display/DOCS/Optimizing+Object+IDs#OptimizingObjectIDs-StoreBinaryGUIDsasBinData%2Cratherthanashexencodedstrings – Sammaye Aug 13 '12 at 21:59
  • Which is what your actually doing atm, sorry didnt read question fully. – Sammaye Aug 13 '12 at 22:00
  • you might want to check an answer to related question of mine: http://stackoverflow.com/a/22607171/253098 – SystematicFrank Mar 24 '14 at 11:17

2 Answers2

18

In addition to gregor's answer, using Guids will currently prevent the use of the new Aggregation Framework as it is represented as a binary type. Regardless, you can do what you are wanting in an easier way. This will let the mongodb bson library handle doing the conversions for you.

public class MyClass
{
  [BsonRepresentation(BsonType.String)]
  public Guid Id { get; set;}
}
Craig Wilson
  • 12,174
  • 3
  • 41
  • 45
5

The drawbacks are that mongodb is optimised to use BSON ObjectID's so it will be slightly less efficient to use strings as ObjectID's. Also if you want to use range based queries on string ObjectIDs then a lexicographic compare will be used which may give different results than you expect. Other than that you can use strings as ObjectIDs. See Optimizing ObjectIDs http://www.mongodb.org/display/DOCS/Optimizing+Object+IDs

geakie
  • 1,458
  • 9
  • 9