向 MongoDB 集合哈希字段添加索引
我有一个 MongoDB 集合,我想在其上添加索引。出于本文的目的,我们假设集合名称为 Cats
。我在 Cats
集合上有一个哈希键,因此如果您执行 db.cats.findOne();
,它将如下所示:
> db.cats.findOne();
{
"_id" : ObjectId("4f248f8ae4b0b775c9eb002d"),
"metaData" : {
"type" : "cute",
"id" : "4ed3b6c599114b488be52bc3"
},
....
}
我经常查询(使用 Mongoid ),像这样:
Cat.first(:conditions => { "metaData.id" => an_id }
我真的很希望能够在这里利用索引,但是我并不完全确定我是否应该索引所有metaData或只是metaData.id(我专门针对id进行查询,而且经常)。
我希望能解决这个问题,因为我认为如果我在这里做正确的事情,我可以大大加快查询速度。 ,这是一个唯一的索引,
metaData 也不是一个嵌入的文档,它没有自己的集合,它只是每个 cats 对象中具有 1:1 映射的哈希。
I have a MongoDB collection that I would like to add an index on. For the purpose of this post, let's say the collection name is Cats
. I have a hash key on the Cats
collection so if you do db.cats.findOne();
it'll look like the following:
> db.cats.findOne();
{
"_id" : ObjectId("4f248f8ae4b0b775c9eb002d"),
"metaData" : {
"type" : "cute",
"id" : "4ed3b6c599114b488be52bc3"
},
....
}
I query very often (using Mongoid), with something like this:
Cat.first(:conditions => { "metaData.id" => an_id }
I'd really like to be able to take advantages of indexes here, but I'm not entirely sure if I should index all of metaData or just metaData.id (I query against id specifically, and very often).
Would love any solution to this problem because I think I can dramatically speed up queries if I do the right thing here. Also, this is a unique index.
also metaData is not an embedded document. it does not have its own collection. it is simply a hash with a 1:1 mapping in each cats object.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您只需在嵌入文档上定义一个索引即可。此处介绍:
http://www.mongodb.org/display/DOCS/ Indexes#Indexes-UsingDocumentsasKeys
对于您的具体示例,这将是:
要比较您的结果,请使用 .explain() 在 shell 中执行一些标准查询,以比较速度和没有索引。如果您没有进行大量查询,您可能需要提示要使用的索引,以便它不会缓存“最佳”索引(不要忘记默认情况下 _id 上有一个索引)。更多解释信息请参见:
http://www.mongodb.org/display/DOCS/Explain
You can just define an index on the embedded document. This is covered here:
http://www.mongodb.org/display/DOCS/Indexes#Indexes-UsingDocumentsasKeys
For your specific example, this would be:
To compare your results do some of your standard queries in the shell with a .explain() to compare the speed with and without the index. If you are not doing a lot of queries you might need to hint the index to use so that it doesn't cache the "best" index (don't forget there is one on _id by default). More explain info here:
http://www.mongodb.org/display/DOCS/Explain