- If you have a column named
Id, id 或 _id
, in your strongly typed TDocument
class (the item type in a collection), then a column named "_id"
will be generated in Mongo. It will also create an index f或 that column. You get a duplicate key err或
exception if trying to insert an item with a key that already exists.
public ObjectId Id {get; set;}
将使用ObjectId
的类型生成器
_id: ObjectId("57ade20771e59f422cc652d9")
同样地:
public Guid _id { get; set; }
将使用Guid生成器生成类似smth的
"_id" : BinData(3,"s2Td7qdghkywlfMSWMPzaA==")
还有以下所有属性
public int Id { get; set; }
public string id { get; set; }
public byte[] _id { get; set; }
如果未指定,将使用每种类型的默认值作为索引列.
[BsonId]
为您提供了任意命名索引的灵活性.
这两个都是索引:
[BsonId]
public Guid SmthElseOtherThanId { get; set; }
[BsonId]
public string StringId { get; set; }
然而
public Guid SmthElseOtherThanId { get; set; }
public string StringId { get; set; }
不会是索引,mongodb仍将在内部使用_id
.
同样的逻辑,
public ObjectId SmthElseOtherThanId {get; set;}
没有[BsonId]
个装饰将不会成为索引列.
[BsonRepresentation]
可以让你在Mongo类型和internal类型之间切换.网络类型,if there's a conversion between them.
有
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public ObjectId Id { get; set; }
与以下内容相同:
public ObjectId 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 int Id { get; set; }
will fail with a ObjectId not a valid representation f或 a ByteArraySerializer / Int32Serializer
message.
但是
[BsonId]
[BsonRepresentation(BsonType.String)]
public int StringId { get; set; }
会没事的.