MongoDB 在使用 $exists 运算符检查字段是否存在时可以使用索引吗? [英] Can MongoDB use an index when checking for existence of a field with $exists operator?
问题描述
如果我的 users
集合中有如下所示的数据:
If I have data in my users
collection that looks like:
{ name: '...',
email: '...',
...,
photos: {
123: { url: '...', title: '...', ... },
456: { url: '...', title: '...', ... },
...
}
}
我想找到哪个用户拥有照片 ID 127,然后我使用查询:
And I want to find which user owns photo id 127, then I am using the query:
db.users.find( {'photos.127': {'$exists' => true} } );
我已经尝试过了,但似乎不可能让 MongoDB 使用索引来进行此查询.我尝试的索引是:db.users.ensureIndex({photos:1});
.当我使用 explain()
时,mongo 告诉我它使用的是 BasicCursor(即没有使用索引).
I've tried, but it doesn't seem possible to get MongoDB to use an index for this query. The index I tried was: db.users.ensureIndex({photos:1});
. And when I used explain()
mongo told me it was using a BasicCursor (i.e., no index was used).
是否可以创建一个 mongo 将用于此查询的索引?
Is it possible to create an index that mongo will use for this query?
推荐答案
更新:
似乎 $exists
查询现在根据这些票正确使用索引$exists 查询应该使用索引 &{$exists: false} 不会使用索引
Seems $exists
queries use index properly now based on these tickets
$exists queries should use index & {$exists: false} will not use index
旧答案:
不,没有办法告诉 mongodb 使用索引进行存在查询.索引与数据完全相关.由于$exists 只与键(字段)相关,所以不能在索引中使用.
No, there is no way to tell mongodb to use index for exists query. Indexing is completely related to data. Since $exists is only related to the keys (fields) it cant be used in indexes.
$exists 只是验证给定的键(或字段)是否存在于文档中.
$exists just verifies whether the given key (or field) exists in the document.
这篇关于MongoDB 在使用 $exists 运算符检查字段是否存在时可以使用索引吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!