如何索引“或”在 MongoDB 中?

发布于 2024-12-11 07:57:04 字数 233 浏览 0 评论 0原文

假设我有很多与此类似的文档...

{
    name: 'alex',
    city: 'LA',
    about: 'designer',
}

db.people.find({'name':'alex', $or: [{'city':'LA'}, {'about':'designer'}] });

如果我想查询它,如何对其建立索引?每次有“或”时都需要 2 个索引吗?

Let's say I have many documents similar to this...

{
    name: 'alex',
    city: 'LA',
    about: 'designer',
}

db.people.find({'name':'alex', $or: [{'city':'LA'}, {'about':'designer'}] });

If I want to query that, how do I index it? Do I need 2 indexes every time I have an "or"?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ι不睡觉的鱼゛ 2024-12-18 07:57:04

索引中的第一个词始终是官方 Mongo 索引文档

为了更直接地回答这个问题,如果您希望查询不仅仅对“名称”使用索引,则需要为所有三个字段建立索引。虽然这可以通过三个单独的索引来完成,但一对复合索引可能会给出更好的结果:

db.people.ensureIndex({name:1, city:1});
db.people.ensureIndex({name:1, about:1});

但是,在选择任何选项之前,我会利用 Mongo 的 解释方法 确定每个索引相对于无索引查询给您带来的收益(在与预期生产一样大的数据集上进行测试一)。我会特别注意每个索引组合的“nscanned”和“nscannedObjects”属性,并使用“indexOnly”和“isMultiKey”验证是否正在使用所需的索引。

最后一点,过度索引也会导致性能问题——如果没有,我们就不必确保索引。确保您需要的索引读取速度增益大于这些索引的写入速度损失。

The first word in indexing is always the official Mongo index documentation.

To answer this question more directly, if you want the query to use indexing on more than just "name", you need an index for all three fields. While this can be done via three separate indexes, a pair of compound indexes might give better results:

db.people.ensureIndex({name:1, city:1});
db.people.ensureIndex({name:1, about:1});

Before settling on any option, however, I'd utilize Mongo's explain method to determine what gains each index is giving you over an index-less query (testing on a data set as large as your expected production one). I'd pay particular attention to the "nscanned", and "nscannedObjects" properties with each combination of index, as well as verify that the desired index is being used using "indexOnly" and "isMultiKey".

As a final note, over-indexing can cause performance issues as well—if they didn't, we wouldn't have to ensure indexes. Be sure that you need the read speed gains of the indexes more than the write speed losses from those indexes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文