MongoDB:“Where”选择的复合索引

时间:2016-10-26 12:10:40

标签: mongodb compound-index

我有以下MongoDB架构:

  mandate: {
    type: mongo.Schema.Types.ObjectId,
    ref: 'Mandate',
    required: true
  },
  observer: {
    type: mongo.Schema.Types.ObjectId,
    ref: 'Observer',
    required: true
  },
  value: {
    type: Number,
    required: true
  },
  observedAt: {
    type: Date,
    required: true
  }

此馆藏拥有大量数据。

我以下列方式询问数据: 给我所有数据   观察2015年至2016年     哪里       observer =“a”和       任务=“b”

对于3个领域的复合索引是否有最佳实践方法(观察者,任务,观察过)?

今天,我这样做:

schema.index({
  mandate: 1,
  observer: 1,
  observedAt: -1
});

这是正确的方法吗?

1 个答案:

答案 0 :(得分:0)

如果你总是会查询所有这3个字段,就像在你的例子中一样,那么是的,这很好。另外,因为您使用observedAt作为最后一个索引,您还可以sort使用该字段,它仍将使用索引进行排序阶段。

但是如果您的查询可以使用更少或更多的字段进行更改,那么它可能不是最佳选择。在这里阅读更多相关内容,特别注意示例

https://docs.mongodb.com/manual/core/index-compound/