在不使用 _id 字段的情况下在 mongodb 中查找文档的最快方法

Fastest way to find a document in mongodb without using _id field

这是我要使用的示例文档。

{
    "_id"       : ObjectId("5cc6ccec131355bb173c64ba"),
    "username"  : "user1",
    "firstname" : "john",
    "lastname"  : "doe"
}

我每次都需要使用 username 字段查找文档。

我使用了 hashed index 但是,它不允许将其设为 unique 字段。

{
    "ok"       : 0,
    "errmsg"   : "Currently hashed indexes cannot guarantee uniqueness. Use a regular index.",
    "code"     : 16764,
    "codeName" : "Location16764"
}

如果有大约 1M 的项目,通过 username 字段查找项目的最快方法是什么?

选项 1: 创建唯一索引。即使有 100 万条记录,我预计也不会出现任何性能问题。即使集合在 5 个成员的副本集中大于 10 亿,我也能获得不错的性能。

db.members.createIndex( { "username": 1 }, { unique: true } )

选项 2: 将用户名存储到 _id 字段中,因为您知道它是唯一的。您将无法使用 _id 字段来检测记录的创建时间,因此如果您需要该功能,则需要存储带有时间戳的另一个字段。