【问题标题】:Is a compound index needed for querying on one field and using another for sorting?查询一个字段并使用另一个字段进行排序是否需要复合索引?
【发布时间】:2023-03-24 10:15:01
【问题描述】:

在 MongoDB 中,假设我有以下查询:

db.things.find({ name: 'some string' }).sort({ age: -1 })

我知道为age 建立索引有助于提高性能,但我是分别为nameage 创建索引,还是作为一个复合索引创建?

db.things.createIndex({ name: 1, age: -1 })

【问题讨论】:

    标签: mongodb indexing


    【解决方案1】:

    创建复合索引。 Mongo DB 的文档在这里更详细地介绍:

    https://docs.mongodb.com/manual/tutorial/sort-results-with-indexes/

    从那个页面:

    以下操作可以使用索引来获取排序顺序:

    ...

    db.data.find( { a: 5 } ).sort( { b: 1, c: 1 } ) ---------------------- ------------- { a: 1 , b: 1, c: 1 }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多