MongoDB 索引:对象键与字符串数组

Geo*_*ess 6 indexing performance schema mongoose mongodb

我是 MongoDB 的新手,一直在研究模式设计和索引。我知道您可以对属性进行索引,而不管其值(ID、数组、子文档等)如何,但我不知道对字符串数组或嵌套对象的键进行索引是否有性能优势。

这是我正在考虑的两种场景的示例(在 Mongoose 中):

// schema
mongoose.Schema({
    visibility: {
        usa: Boolean,
        europe: Boolean,
        other: Boolean
    }
});
// query
Model.find({"visibility.usa": true});
Run Code Online (Sandbox Code Playgroud)

或者

// schema
mongoose.Schema({
    visibility: [String] // strings could be "usa", "europe", and/or "other"
});
// query
Model.find({visibility: "usa"});
Run Code Online (Sandbox Code Playgroud)

文档可以具有一种、两种或全部三种可见性选项。

此外,如果我采用布尔对象设计,我可以简单地索引可见性字段,还是需要在美国、欧洲和其他国家建立索引?

Avi*_*Avi 5

在 MongoDB 中,在字符串数组上创建索引会生成 multiKey 索引,其中数组中的所有字符串形成索引键并指向同一文档。因此,在您的情况下,它与嵌套对象键的工作方式相同。

如果您采用布尔设计,则可以将索引放在可见性字段上。您可以进一步阅读MongoDB Mulitkey Indexing