MongoDB 使用 _id
作为默认的字段来存储文档的唯一标识符(primary key)。这个决策背后有几个原因:
-
唯一性: MongoDB 设计
_id
字段是为了确保集合中的每个文档都能够被唯一地标识。MongoDB 为每个新文档自动生成一个 ObjectId 类型的_id
值,这个值在全局范围内是唯一的,这意味着即使在不同的服务器或集群上,两个文档不会有相同的_id
。 -
一致性: 使用
_id
作为所有文档的标准字段名,MongoDB 为开发人员提供了一致的接口来引用文档的主键。这种一致性简化了数据模型的设计,并且使得开发者可以编写更加通用的代码来处理不同的文档。 -
索引: 在 MongoDB 中,每个集合会自动对
_id
字段建立一个唯一索引。这样的设计保证了文档的快速查找和高效的数据完整性检查。如果没有这个默认的索引,开发人员需要手动为他们选择的主键字段建立索引,这会增加开发的复杂性。
例如,假设我们有一个用户集合(collection),其中包含了许多用户文档(document)。每个文档都会自动有一个 _id
字段,如下:
json{ "_id": ObjectId("507f191e810c19729de860ea"), "name": "John Doe", "email": "john.doe@example.com" }
即使开发者可以选择使用自定义的字段(比如 id
)作为文档的标识符,但是为了保持一致性和利用 MongoDB 内建的索引,通常建议使用默认的 _id
字段。如果有特定的需要,开发者可以在应用层将 _id
映射到 id
或其他任何他们希望的字段上。这种情况下,开发者需要负责维护额外字段的唯一性和索引。