用BsonRepresentation(BsonType.ObjectId)与BsonId与ObjectId在C#中修饰属性之间的区别

用BsonRepresentation(BsonType.ObjectId)与BsonId与ObjectId在C#中修饰属性之间的区别,c#,mongodb,mongodb-query,C#,Mongodb,Mongodb Query,我是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

我是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)如果在强类型的
t文档
类(集合中的项目类型)中有一个名为
Id、Id或_Id
的列,那么将在Mongo中生成一个名为
“\u Id”
的列。它还将为该列创建索引。如果尝试插入具有已存在密钥的项,则会出现重复密钥错误异常

public ObjectId{get;set;}
将使用
ObjectId
的类型生成器,它看起来像
\u Id:ObjectId(“57ade20771e59f42cc652d9”)

public Guid\u id{get;set;}
将使用Guid生成器生成类似于
“\u id”:BinData(3,“s2Td7qdghkywlfMSWMPzaA=”)的smth

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

2)
[BsonId]
为您提供了按任何方式命名索引的灵活性<代码>[BsonId]公共Guid SMTHELSEOTHETHANID{get;set;}和
[BsonId]公共字符串StringId{get;set;}
将作为索引<代码>公共Guid SMTHELSEOthernId{get;set;}和
公共字符串StringId{get;set;}
不会。mongodb仍将在内部使用
\u id

同样的逻辑,
public ObjectId smthelsetherthanId{get;set;}
没有
[BsonId]
装饰将不会成为索引列

3)
[BsonRepresentation]
允许您处理Mongo类型与内部.Net类型之间的转换

拥有
[BsonId][BsonRepresentation(BsonType.ObjectId)]公共ObjectId{get;set;}
公共ObjectId{get;set;}
相同

然而,拥有
[BsonId][BsonRepresentation(BsonType.ObjectId)]公共字符串Id{get;set;}
则不同。Mongo将自己自动生成对象id,但是您将能够在.net中使用字符串、过滤查询等,因为对象id和字符串之间存在转换

拥有
[BsonId][BsonRepresentation(BsonType.ObjectId)]公共字节[]Id{get;set;}
[BsonId][BsonRepresentation(BsonType.ObjectId)]公共int Id{get;set;}
将失败,因为
ObjectId不是bytearlyserializer/Int32Serializer的有效表示形式


但是,
[BsonId][BsonRepresentation(BsonType.String)]public int StringId{get;set;}
就可以了。

谢谢,类型转换的任何性能损失,在规模上都很明显。