【问题标题】:is it advised to created two separate indexes for the query to filter on one field and sort on another?是否建议为查询创建两个单独的索引以过滤一个字段并在另一个字段上排序?
【发布时间】:2012-01-30 05:56:27
【问题描述】:

我有一个类似以下的查询

find( { a : { $gt: 3 } } ).sort( { b : -1 } )

是否建议为字段a和b分别创建索引?

【问题讨论】:

    标签: mongodb indexing mongodb-indexes


    【解决方案1】:

    不,使用compound 索引查询会更快:

    db.items.ensureIndex({a:1, b:-1});
    

    您还可以通过explain 命令确保您的查询使用索引。

    【讨论】:

    • 谢谢!使用 Morphia 时,如何为地理字段和另一个字段(计数器字段)定义复合索引?目前我有一个地理字段的@Indexed(value=IndexDirection.GEO2D) 注释和另一个字段的@Indexed(value=IndexDirection.DESC)?
    • @tom: 创建compound index: db.places.ensureIndex( { location : "2d" , counter : -1 } ); 并确保它与explain 命令一起使用。
    猜你喜欢
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 2014-05-25
    • 2015-02-14
    • 1970-01-01
    • 2013-06-22
    • 1970-01-01
    • 2016-07-20
    相关资源
    最近更新 更多