使用BsonRepresentation(BsonType.ObjectId)与BsonId对比ObjectId来装饰C#中的属性之间的区别

我是mongodb的新手并且很喜欢不用担心架构的问题,我有一个问题,假设你想在mongo中使用Id属性而mongo使用ObjectId来表示属性Id,到目前为止我看到你可以拥有或装饰一个Id如下,

 public ObjectId Id {get; set;} //or [BsonId] public string Id {get; set;} //or [BsonId] [BsonRepresentation(BsonType.ObjectId)] public string Id {get; set;} 

任何人都可以向我解释为什么大多数人会选择最后一种类型,以及最新情况以及灵活性如何帮助。 谢谢?

1)如果在强类型的TDocument类(集合中的项类型)中有一个名为Id, id or _id的列,则会在Mongo中生成名为"_id"的列。 它还将为该列创建索引。 如果尝试插入具有已存在的键的项,则会出现duplicate key errorexception。

public ObjectId Id { get; set; } 将使用ObjectId的类型生成器,它看起来像_id: ObjectId("57ade20771e59f422cc652d9")

public Guid _id { get; set; } 将使用Guid生成器生成类似"_id" : BinData(3,"s2Td7qdghkywlfMSWMPzaA==") smth "_id" : BinData(3,"s2Td7qdghkywlfMSWMPzaA==")

public int Id { get; set; }public string id { get; set; } public string id { get; set; } public string id { get; set; }public byte[] _id { get; set; } public byte[] _id { get; set; } 如果未指定,也将使用每种类型的默认值的索引列。

2) [BsonId]为您提供了以任何方式命名索引的灵活性。 [BsonId] public Guid SmthElseOtherThanId { get; set; }[BsonId] public string StringId { get; set; } [BsonId] public string StringId { get; set; } 将是索引; public Guid SmthElseOtherThanId { get; set; }public string StringId { get; set; } public string StringId { get; set; } 不会。 mongodb仍将在内部使用_id

相同的逻辑, public ObjectId SmthElseOtherThanId {get; set;} public ObjectId SmthElseOtherThanId {get; set;}没有[BsonId]装饰将不是索引列。

3) [BsonRepresentation]允许您使用Mongo类型与内部.Net类型, 如果它们之间存在转换

拥有[BsonId] [BsonRepresentation(BsonType.ObjectId)] public ObjectId Id { get; set; } [BsonId] [BsonRepresentation(BsonType.ObjectId)] public ObjectId Id { get; set; } [BsonId] [BsonRepresentation(BsonType.ObjectId)] public ObjectId Id { get; set; }public ObjectId Id { get; set; } public ObjectId Id { get; set; } public ObjectId Id { get; set; }

拥有[BsonId] [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set; } [BsonId] [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set; } 然而,是不同的。 Mongo会自动生成对象ID,但是你可以在.net中使用字符串,过滤查询等,因为对象id和字符串之间存在转换。

[BsonId] [BsonRepresentation(BsonType.ObjectId)] public byte[] Id { get; set; } [BsonId] [BsonRepresentation(BsonType.ObjectId)] public byte[] Id { get; set; } [BsonId] [BsonRepresentation(BsonType.ObjectId)] public byte[] Id { get; set; }[BsonId] [BsonRepresentation(BsonType.ObjectId)] public int Id { get; set; } [BsonId] [BsonRepresentation(BsonType.ObjectId)] public int Id { get; set; } [BsonId] [BsonRepresentation(BsonType.ObjectId)] public int Id { get; set; }将失败, ObjectId not a valid representation for a ByteArraySerializer / Int32Serializer消息ObjectId not a valid representation for a ByteArraySerializer / Int32Serializer

但是[BsonId] [BsonRepresentation(BsonType.String)] public int StringId { get; set; } [BsonId] [BsonRepresentation(BsonType.String)] public int StringId { get; set; } 会没事的。