MongoDB多个单个索引

时间:2017-02-10 19:39:30

标签: mongodb mongoose

我对mongodb中的索引有点不清楚。

下面我有mongoose条目的架构(book)。它有一个owner和一个requestee

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const bookSchema = Schema({
    owner    : { type: Schema.Types.ObjectId, ref: 'User', index: true },
    title    : String,
    author   : String,
    image    : String,
    added    : Date,
    requestee: { type: Schema.Types.ObjectId, ref: 'User', index: true },
}, {collection: 'books'})

module.exports = mongoose.model("Book", bookSchema);

我想要做的是能够从两个角度进行查询。

对于本书的owner

Book.find({owner: ObjectId(user._id)})

这可以告诉我是否有人要求这本书

对于被请求者:

Book.find({requestee: ObjectId(requestee._id)})

这将告诉我被请求者提出的请求。

我不清楚我的上述内容在索引方面是否正确。我可以拥有多个单键索引,还是我正在扫描每个寻找匹配项的文档?

从shell运行查询似乎有效但又不知道这是否正确。

1 个答案:

答案 0 :(得分:2)

您可以在查询上运行explain以查看索引使用情况。如果对您的用例更好,请查看复合索引。

更多信息 - https://docs.mongodb.com/manual/tutorial/measure-index-use/

相关问题