Learn the "why" behind slow queries and how to fix them in our 2-Part Webinar.
Register now >
Docs 菜单
Docs 主页
/ /

$exists(查询谓词运算操作符)

$exists

$exists 运算符匹配包含或不包含指定字段的文档,包括字段值为 null 的文档。

注意

MongoDB$exists 与SQL操作符exists 不对应。对于SQLexists ,请参阅$in

对于Atlas Searchexists ,请参阅Atlas文档中的 exists ( MongoDB Search Operator)。

可以使用 $exists 查找托管在以下环境中的部署:

  • MongoDB Atlas:用于云中 MongoDB 部署的完全托管服务

注意

表达式不支持$exists操作符。要检查表达式中某个字段是否存在,可以使用 $type 聚合操作符来检查字段的类型是否为 missing

有关更多信息,请参阅 $type 存在性检查。

要指定 $exists 表达式,请使用以下原型:

{ field: { $exists: <boolean> } }

<boolean> 为 true 时,$exists 匹配包含该字段的文档,包括字段值为 null 的文档。如果 <boolean> 为 false,则查询仅返回不包含该字段的文档。

对于存储在 MongoDB Atlas 中的数据,您可以在运行 查询时使用 Atlas Search exists(MongoDB Search Operator) $search操作符。$exists$search在 之后运行 的性能低于运行带有$search exists(MongoDB搜索操作符) 操作符的 。

要学习;了解有关此操作符的Atlas Search版本的更多信息,请参阅Atlas文档中的exists ( MongoDB Search Operator)操作符。

本页上的示例使用sample_mflix示例数据集中的数据。有关如何将此数据集加载到自管理MongoDB 部署中的详细信息,请参阅加载示例数据集。如果对示例数据库进行了任何修改,则可能需要删除并重新创建数据库才能运行本页上的示例。

考虑以下示例:

db.movies.find( { rated: { $exists: true, $nin: [ "R", "PG-13" ] } } ).limit(5)

此查询选择5 movies集合中的 个文档,其中存在rated 字段且其值不等于"R""PG-13"

sample_mflix数据库中的 movies集合包含的文档存在某些字段,但缺少其他字段。示例,rated字段存在于 11,455 文档中,但在其余的 9,894 文档中不存在。

以下查询将指定查询谓词 rated: { $exists: true }

db.movies.find( { rated: { $exists: true } }, { _id: 0, title: 1, rated: 1 } ).limit( 3 )

结果由三个包含字段rated 的文档组成:

[
{ title: 'The Great Train Robbery', rated: 'TV-G' },
{ title: 'A Corner in Wheat', rated: 'G' },
{ title: 'Traffic in Souls', rated: 'TV-PG' }
]

以下查询将指定查询谓词 rated: { $exists: false }

db.movies.find( { rated: { $exists: false } }, { _id: 0, title: 1, year: 1 } ).limit( 3 )

结果由三个不包含字段rated 的文档组成:

[
{
title: 'Winsor McCay, the Famous Cartoonist of the N.Y. Herald and His Moving Comics',
year: 1911
},
{ title: 'Gertie the Dinosaur', year: 1914 },
{ title: 'In the Land of the Head Hunters', year: 1914 }
]

下表比较使用稀疏索引和非稀疏索引的 $exists 查询性能:

$exists 查询
使用稀疏索引
Using a Non-Sparse Index

{ $exists: true }

最高效。MongoDB 可以进行精确匹配,不需要 FETCH

比不含索引的查询更高效,但仍需FETCH

{ $exists: false }

无法使用索引,需要 COLLSCAN

需要使用 FETCH

以下查询检查集合中的所有文档:对使用非稀疏索引的字段使用 { $exists: true } 或对未编入索引的字段使用 { $exists: true }。为了提高性能,请在 field 上创建稀疏索引,如以下场景所示:

  1. movies集合包含的文档中,某些文档中存在 metacritic字段,而其他文档中不存在。在 21,349 文档中,6,964 有 metacritic字段,而 14,385 没有。

  2. metacritic 字段上创建稀疏索引

    db.movies.createIndex(
    { metacritic: 1 },
    { name: "metacriticSparseIndex", sparse: true }
    )
  3. 以下示例计算 metacritic 字段具有值(包括 null)并使用稀疏索引的文档:

    db.movies.countDocuments( { metacritic: { $exists: true } } )

    该示例返回 6964。该操作不会计算缺少 metacritic字段的文档。

提示

如果只需 field 具有非空值的文档,您可以:

  • 可以使用 $ne: null 代替 $exists: true

  • 不需要在 field 上使用稀疏索引

例如,使用 movies 集合:

db.movies.countDocuments( { metacritic: { $ne: null } } )

该示例返回 6964。缺少 metacritic 值或 metacritic 值为空的文档不予计数。

后退

数据类型

在此页面上