为此查询创建索引的策略是什么?

时间:2017-06-13 10:47:24

标签: mongodb indexing mongoose

我为每个帖子都有一个评论模型,

const CommentSchema = new mongoose.Schema({
    author: { type: ObjectID, required: true, ref: 'User' },
    thread: { type: ObjectID, required: true, ref: 'Thread' },
    parent: { type: ObjectID, required: true, ref: 'Comment' },
    text: { type: String, required: true },
}, {
    timestamps: true,
});

除了_id的单个查询外,我想通过这种方式查询数据库:

范围查询

const query = {
    thread: req.query.threadID,
    _id: { $gt: req.query.startFrom }
};

CommentModel.find(query).limit(req.query.limit);

我的目的是找到与线程相关的注释,然后获取结果的一部分。看来这个查询按预期工作。我的问题是:

  1. 这是满足我要求的正确方法吗?

  2. 如何正确索引字段?这是一个复合索引还是我需要分别索引每个字段?我检查了explain()的结果,只要其中一个查询字段包含索引,inputStage.stage将始终包含IXSCAN而不是COLLSCAN?这是检查查询性能的关键信息吗?

  3. 这是否意味着每次我需要根据一个字段查找时,我需要为这些字段制作索引?让我们说我想搜索作者发布给特定帖子的所有评论。

  4. 这样的代码:

    const query = {
        thread: req.query.threadID,
        author: req.query.authorID,
    };
    

    我是否需要为此要求创建复合索引?

1 个答案:

答案 0 :(得分:1)

如果您想通过多个字段进行查询,则必须创建复合索引

例如

const query = {
    thread: req.query.threadID,
    author: req.query.authorID,
};

如果您想使用此查询,则必须创建复合索引,如:

db.comments.createIndex( { "thread": 1, "author": 1 } );

然后,索引支持对项目字段以及项目和库存字段的查询:

db.comments.find( { thread: "threadName" } )
db.comments.find( { thread: "threadName", author: "authorName" } 

但不支持这个

db.comments.find( { author: "authorName", thread: "threadName" } 

如果你为{ "thread": 1, "author": 1, "parent": 1 }创建索引,那么对于下面的命令查询支持索引

  

thread字段,

     

thread字段和author字段

     

thread字段和author字段以及parent字段。

不支持以下命令

  

author字段,

     

parent字段或

     

authorparent字段。

For more read this

相关问题