我是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;}

有谁能向我解释一下为什么大多数人 Select 最后一种类型,发生了什么,以及这种灵活性是如何发挥作用的.谢谢

推荐答案

  1. 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; }

如果未指定,将使用每种类型的默认值作为索引列.

  1. [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]个装饰将不会成为索引列.

  1. [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; }

会没事的.

Mongodb相关问答推荐

$mod只支持数字类型,不支持MongoDb中的array和int

Mongodb如果数组中有外部键,则将排序应用到查找结果

如何在MongoDB中正确解析佛年?

spring-data-mongodb 上的 TopN 聚合

错误起草的 MongoDB 聚合管道 $match 阶段

MongoDB 更新:如果新值不同,则将旧字段值推送到另一个数组字段

为什么 MongoDB 配置服务器必须只有一个或三个?

更新 MongoDB 中嵌套实体数组中的属性

无法使用机器 ip 连接到 mongodb

根据 Month 删除 mongodb 中的旧记录

在 mongodb 中查找字段的所有非不同值

MongoDB $or 查询

MongoDB中超过2GB的数据库

具有简单密码认证的 MongoDB 副本集

从 id 删除 PyMongo 中的文档

了解 Mongoose 中的关系和外键

如何通过mongoose更新 mongodb 中的对象?

何时使用Singleton单例、Transient和使用 Ninject 和 MongoDB 的请求

在 MongoDB 中比较日期(moment.js)

如何使用 mongodb-java-driver 进行 upsert