如果我的 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?
推荐答案不,没有办法告诉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.
更多推荐
在使用$ exists运算符检查字段是否存在时,MongoDB可以使用索引吗?
发布评论