在使用$ exists运算符检查字段是否存在时,MongoDB可以使用索引吗? [英] Can MongoDB use an index when checking for existence of a field with $exists operator?

查看:177
本文介绍了在使用$ exists运算符检查字段是否存在时,MongoDB可以使用索引吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的 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可以使用索引吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆