MongoDB 在使用 $exists 运算符检查字段是否存在时可以使用索引吗?

编程入门 行业动态 更新时间:2024-10-09 23:13:42
本文介绍了MongoDB 在使用 $exists 运算符检查字段是否存在时可以使用索引吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如果我的 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 运算符检查字段是否存在时可以使用索引吗?

本文发布于:2023-11-09 04:03:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1571351.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可以使用   字段   是否存在   运算符   索引

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!