在MongoDB中创建自定义对象ID [英] Creating custom Object ID in MongoDB

查看:799
本文介绍了在MongoDB中创建自定义对象ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个服务,该服务将使用MongoDB作为存储后端. 该服务将生成用户输入的哈希,然后查看我们的数据集中是否已经存在相同的哈希(+输入).

I am creating a service for which I will use MongoDB as a storage backend. The service will produce a hash of the user input and then see if that same hash (+ input) already exists in our dataset.

哈希将是唯一但随机的(=非增量/顺序的),所以我的问题是:

The hash will be unique yet random ( = non-incremental/sequential), so my question is:

  1. 使用随机值作为对象ID是否合法?示例:

$object_id = new MongoId(HEX-OF-96BIT-HASH);

或者,由于真实的" ObjectID还包含时间戳,machine_id等,MongoDB会将ObjectID与其他服务器生成的ID区别对待吗?

Or will MongoDB treat the ObjectID differently from other server-produced ones, since a "real" ObjectID also contains timestamps, machine_id, etc?

使用随机"值的利弊是什么?我猜想,当新的_id不以任何方式递增时,引擎在插入时更新索引在统计上会更慢-我对此是否正确?

What are the pros and cons of using a 'random' value? I guess it would be statistically slower for the engine to update the index on inserts when the new _id's are not in any way incremental - am I correct on that?

推荐答案

是的,对于对象ID使用随机值是完全可以的,如果要存储的文档的_id字段中存在某个值,则为视为objectId.

Yes it is perfectly fine to use a random value for an object id, if some value is present in _id field of a document being stored, it is treated as objectId.

由于总是索引_id字段和主键,因此需要确保为每个对象生成不同的objectid. 有一些准则可以优化用户定义的对象ID:

Since _id field is always indexed, and primary key, you need to make sure that different objectid is generated for each object. There are some guidelines to optimize user defined object ids :

https://docs.mongodb.com/manual/核心/文档/#the-id-field .

这篇关于在MongoDB中创建自定义对象ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆