简体   繁体   English

索引MongoDB最初不存在的字段

[英]Indexing a field that doesn't exist initially in MongoDB

I have a collection where in initially we have a following structure of a review document 我有一个集合,最初我们具有以下审查文件结构

{
_id:ObjectId(...),
comment:"hi, test comment",
crBy:ObjectId(...)
}

Now when then admin reviews this, a status field gets added to it updating the doc to 现在,当管理员对此进行审查时,会向其添加一个状态字段,从而将文档更新为

   {
    _id:ObjectId(...),
    comment:"hi, test comment",
    crBy:ObjectId(...),
    status:"approved"
    }

For some reasons I can't have status initially and it has to be put in when an admin reviews it and it comes with a value approved or disapproved 由于某些原因,我最初无法获得状态,因此管理员必须对其进行审核,并且其状态为批准或不批准

So now the query to get all reviews created by a user and are approved would be like .... db.reviews.find({"crBy":ObjectId(...),"status":"approved"}) 因此,现在获取用户创建的所有评论并获得批准的查询就像.... db.reviews.find({“ crBy”:ObjectId(...),“ status”:“ approved”})

I am optimizing the reads by creating an index including both crBy and status fields 我正在通过创建包含crBy和status字段的索引来优化读取

My questions are: 我的问题是:

1.Am i creating the index in the right way?

2. I have read that indexes should contain fields that don't change. So in my case status field gets inserted afterwards. How does it
impact my performance?

3. Considering my case, what do you suggest to be the best possible way to optimize reads in such a scenario where a field comes later
on?

Thanks in advance 提前致谢

There is nothing stopping you from creating an index on a key that does not exist. 没有什么可以阻止您在不存在的键上创建索引。 Given your query, your index should mirror it 给定您的查询,您的索引应该镜像它

db.collection.ensureIndex({crBy: 1, status: 1}, {background: 1})

I've added in the background option. 我添加了后台选项。 This will ensure that while rebuilding this index, it will not block other operations. 这将确保在重建此索引时,它不会阻止其他操作。 It will still have an effect on the performance of the update to status. 它仍然会影响状态更新的性能。 The only reason it's suggested to make an index on something that doesnt change, is because of the overhead of rebuilding the index upon write, in this case, you'll be gaining read speed because of this index, so it is worth it. 建议在不变的对象上建立索引的唯一原因是由于在写入时重建索引的开销,在这种情况下,由于有了该索引,您将获得读取速度,因此这是值得的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM