我的文档中有一个类型为 int
的唯一 ID 字段。我正在此字段上执行 ensureIndex
,但我的文档仍然包含 _id
。我可以摆脱它吗?
最佳答案
来自 docs ...
If a user tries to insert a document without providing an _id field, the database will automatically generate an object id and store it the _id field.
但是,您可以将自己的值分配给 _id ...
The _id value may be of any type, other than arrays, so long as it is a unique.
更好的问题是,为什么要创建自己的唯一 ID,在其上建立索引并删除自动索引的非常有用的 ObjectID _id?
所有官方驱动程序都使用 ObjectID,它有很多非常好的方面:
它有一个内置的时间戳(所以你不需要存储日期字段 在您的文档中,您可以使用它按日期排序。)
它是一个“全局的、均匀递增的序列号”——即 如果您需要对数据进行分片,它在服务器之间仍然是唯一的, 等等。
关于c++ - MongoDB:是否可以避免使用自动 _id 字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8100660/