$exists

On this page本页内容

Definition定义

$exists

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

When <boolean> is true, $exists matches the documents that contain the field, including documents where the field value is null. <boolean>true,$exists匹配包含该字段的文档,包括字段值为null的文档。If <boolean> is false, the query returns only the documents that do not contain the field. 如果<boolean>false,则查询仅返回不包含该字段的文档。[1]

MongoDB $exists does not correspond to SQL operator exists. MongoDB$exists与SQL运算符exists不对应。For SQL exists, refer to the $in operator.对于SQL exists,请参阅$in运算符。

[1]Starting in MongoDB 4.2, users can no longer use the query filter $type: 0 as a synonym for $exists:false. 从MongoDB 4.2开始,用户不能再将查询筛选器$type:0用作$exists:false的同义词。To query for null or missing fields, see Query for Null or Missing Fields.要查询空字段或缺少的字段,请参阅查询空字段或缺少的字段

Examples示例

Exists and Not Equal To存在且不等于

Consider the following example:考虑下面的例子:

db.inventory.find( { qty: { $exists: true, $nin: [ 5, 15 ] } } )

This query will select all documents in the inventory collection where the qty field exists and its value does not equal 5 or 15.此查询将选择inventory集合中存在qty字段且其值不等于515的所有单据。

Null Values空值

The following examples uses a collection named records with the following documents:以下示例将名为records的集合与以下文档一起使用:

{ a: 5, b: 5, c: null }
{ a: 3, b: null, c: 8 }
{ a: null, b: 3, c: 9 }
{ a: 1, b: 2, c: 3 }
{ a: 2, c: 5 }
{ a: 3, b: 2 }
{ a: 4 }
{ b: 2, c: 4 }
{ b: 2 }
{ c: 6 }

$exists: true

The following query specifies the query predicate a: { $exists: true }:以下查询指定查询谓词a: { $exists: true }

db.records.find( { a: { $exists: true } } )

The results consist of those documents that contain the field a, including the document whose field a contains a null value:结果由包含字段a的文档组成,包括字段a包含null值的文档:

{ a: 5, b: 5, c: null }
{ a: 3, b: null, c: 8 }
{ a: null, b: 3, c: 9 }
{ a: 1, b: 2, c: 3 }
{ a: 2, c: 5 }
{ a: 3, b: 2 }
{ a: 4 }

$exists: false

The following query specifies the query predicate b: { $exists: false }:以下查询指定查询谓词b: { $exists: false }

db.records.find( { b: { $exists: false } } )

The results consist of those documents that do not contain the field b:结果由不包含字段b的文档组成:

{ a: 2, c: 5 }
{ a: 4 }
{ c: 6 }

Starting in MongoDB 4.2, users can no longer use the query filter $type: 0 as a synonym for $exists:false. 从MongoDB 4.2开始,用户不能再将查询筛选器$type:0用作$exists:false的同义词。To query for null or missing fields, see Query for Null or Missing Fields.要查询空字段或缺少的字段,请参阅查询空字段或缺少的字段