Convert .NET Guid to MongoDB ObjectID

后端 未结 4 1508
臣服心动
臣服心动 2021-02-03 22:11

How can I convert a .NET GUID to a MongoDB ObjectID (in C#). Also, can I convert it back again to the same GUID from the ObjectID?

4条回答
  •  一整个雨季
    2021-02-03 22:51

    You can't convert ObjectId into GUID and vice versa, because they are two different things(different sizes, algoritms).

    You can use any type for mongoDb _id including GUID.

    For example in official c# driver you should specify attribute [BsonId]:

    [BsonId]
    public Guid Id {get;set;}
    
    [BsonId]
    public int Id {get;set;}
    

    ObjectId:

    A BSON ObjectID is a 12-byte value consisting of a 4-byte timestamp (seconds since epoch), a 3-byte machine id, a 2-byte process id, and a 3-byte counter. Note that the timestamp and counter fields must be stored big endian unlike the rest of BSON. This is because they are compared byte-by-byte and we want to ensure a mostly increasing order.

    GUID:

    The value of a GUID is represented as a 32-character hexadecimal string, such as {21EC2020-3AEA-1069-A2DD-08002B30309D}, and is usually stored as a 128-bit integer

提交回复
热议问题