Database Manual / Reference / Query Language / Query Predicates / Data Type

$type

Definition定义

$type
$type selects documents where the value of the field is an instance of the specified BSON type(s). 选择field值为指定BSON类型实例的文档。Querying by data type is useful when dealing with highly unstructured data where data types are not predictable.在处理数据类型不可预测的高度非结构化数据时,按数据类型查询非常有用。

Compatibility兼容性

You can use $type for deployments hosted in the following environments:您可以将$type用于在以下环境中托管的部署:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务
  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本

Syntax语法

A $type expression for a single BSON type has the following syntax:单个BSON类型的$type表达式具有以下语法:

{ field: { $type: <BSON type> } }

You can specify either the number or alias for the BSON type.您可以为BSON类型指定编号或别名。

The $type expression can also accept an array of BSON types and has the following syntax:$type表达式还可以接受BSON类型的数组,语法如下:

{ field: { $type: [ <BSON type1> , <BSON type2>, ... ] } }

The above query matches documents where the field value is any of the listed types. The types specified in the array can be either numeric or string aliases.上述查询匹配field值为任何列出类型的文档。数组中指定的类型可以是数字别名或字符串别名。

See Querying by Multiple Data Types for an example.有关示例,请参阅按多种数据类型查询

Available Types describes the BSON types and their corresponding numeric and string aliases.可用类型描述了BSON类型及其相应的数字和字符串别名。

Tip

  • $isNumber - checks if the argument is a number.检查参数是否为数字。
  • $type (Aggregation) - returns the BSON type of the argument.返回参数的BSON类型。

Behavior行为

$type returns documents where the BSON type of the field matches the BSON type passed to $type.返回field的BSON类型与传递给$type的BSON类型匹配的文档。

Arrays数组

For documents where field is an array, $type returns documents in which at least one array element matches a type passed to $type.对于field为数组的文档,$type返回至少有一个数组元素与传递给$type的类型匹配的文档。

Queries for $type: "array" return documents where the field itself is an array.$type: "array"的查询返回字段本身是数组的文档。

Available Types可用类型

The $type operator accepts string aliases for the BSON types in addition to the numbers corresponding to the BSON types. 除了与BSON类型对应的数字外,$type运算符还接受BSON类型的字符串别名。[1]

Type类型Number数字Alias别名Notes备注
Double双精度浮点数1"double"
String字符串2"string"
Object3"object"
Array数组4"array"
Binary data5"binData"
Undefined6"undefined"Deprecated.
ObjectId7"objectId"
Boolean布尔值8"bool"
Date9"date"
Null10"null"
Regular Expression正则表达式11"regex"
DBPointer12"dbPointer"Deprecated.
JavaScript13"javascript"
Symbol14"symbol"Deprecated.
JavaScript with scope15"javascriptWithScope"Deprecated.
32-bit integer16"int"
Timestamp17"timestamp"
64-bit integer18"long"
Decimal12819"decimal"
Min key-1"minKey"
Max key127"maxKey"

$type supports the number alias, which matches against the following BSON types:支持与以下BSON类型匹配的number别名:

For examples, see Examples.有关示例,请参阅示例

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

MinKey and MaxKey

MinKey and MaxKey are used in comparison operations and exist primarily for internal use. 用于比较操作,主要用于内部使用。For all possible BSON element values, MinKey is always the smallest value while MaxKey is always the greatest value.对于所有可能的BSON元素值,MinKey始终是最小值,而MaxKey始终是最大值。

Querying for minKey or maxKey with $type only returns fields that match the special MinKey or MaxKey values.使用$type查询minKeymaxKey只会返回与特殊minKeymaxKey值匹配的字段。

Suppose that the data collection has two documents with MinKey and MaxKey:假设data集合有两个具有MinKeyMaxKey的文档:

db.data.insertMany( [
{ _id : 1, x : { "$minKey" : 1 } },
{ _id : 2, y : { "$maxKey" : 1 } }
] )

The following query returns the document with _id: 1:以下查询返回_id1的文档:

db.data.find( { x: { $type: "minKey" } } )

The following query returns the document with _id: 2:以下查询返回_id2的文档:

db.data.find( { y: { $type: "maxKey" } } )

Examples示例

Querying by Data Type按数据类型查询

The addressBook contains addresses and zipcodes, where zipCode has string, int, double, and long values:addressBook包含地址和邮政编码,其中zipCodestringintdoublelong值:

db.addressBook.insertMany( [
{ _id : 1, address : "2030 Martian Way", zipCode : "90698345" },
{ _id : 2, address : "156 Lunar Place", zipCode : 43339374 },
{ _id : 3, address : "2324 Pluto Place", zipCode : Long(3921412) },
{ _id : 4, address : "55 Saturn Ring" , zipCode : Int32(88602117) },
{ _id : 5, address : "104 Venus Drive", zipCode : ["834847278", "1893289032"] }
] )

The following queries return all documents where zipCode is the BSON type string or is an array containing an element of the specified type:以下查询返回所有zipCodeBSON类型string或包含指定类型元素的数组的文档:

db.addressBook.find( { zipCode : { $type : 2 } } );
db.addressBook.find( { zipCode : { $type : "string" } } );

These queries return:这些查询返回:

{ _id : 1, address : "2030 Martian Way", zipCode : "90698345" }
{ _id : 5, address : "104 Venus Drive", zipCode : [ "834847278", "1893289032" ] }

The following queries return all documents where zipCode is the BSON type double or is an array containing an element of the specified type:以下查询返回所有zipCodeBSON类型double或包含指定类型元素的数组的文档:

db.addressBook.find( { zipCode : { $type : 1 } } );
db.addressBook.find( { zipCode : { $type : "double" } } );

These queries return:这些查询返回:

{ _id : 2, address : "156 Lunar Place", zipCode : 43339374 }

The following query uses the number alias to return documents where zipCode is the BSON type double, int, or long or is an array containing an element of the specified types:以下查询使用number别名返回文档,其中zipCode是BSON类型doubleintlong,或者是一个包含指定类型元素的数组:

db.addressBook.find( { zipCode : { $type : "number" } } )

These queries return:这些查询返回:

{ _id : 2, address : "156 Lunar Place", zipCode : 43339374 }
{ _id : 3, address : "2324 Pluto Place", zipCode : Long(3921412) }
{ _id : 4, address : "55 Saturn Ring", zipCode : 88602117 }

Querying by Multiple Data Types按多种数据类型查询

The grades collection contains names and averages, where classAverage has string, int, and double values:grades集合包含名称和平均值,其中classAverage具有stringintdouble值:

db.grades.insertMany( [
{ _id : 1, name : "Alice King" , classAverage : 87.333333333333333 },
{ _id : 2, name : "Bob Jenkins", classAverage : "83.52" },
{ _id : 3, name : "Cathy Hart", classAverage: "94.06" },
{ _id : 4, name : "Drew Williams" , classAverage : Int32("93") }
] )

The following queries return all documents where classAverage is the BSON type string or double or is an array containing an element of the specified types. The first query uses numeric aliases while the second query uses string aliases.以下查询返回所有classAverage为BSON类型stringdouble或包含指定类型元素的数组的文档。第一个查询使用数字别名,而第二个查询使用字符串别名。

db.grades.find( { classAverage : { $type : [ 2 , 1 ] } } );
db.grades.find( { classAverage : { $type : [ "string" , "double" ] } } );

These queries return the following documents:这些查询返回以下文档:

{ _id : 1, name : "Alice King", classAverage : 87.33333333333333 }
{ _id : 2, name : "Bob Jenkins", classAverage : "83.52" }
{ _id : 3, name : "Cathy Hart", classAverage : "94.06" }

Querying by MinKey and MaxKey按MinKey和MaxKey查询

The restaurants collection uses minKey for any grade that is a failing grade:restaurants集合使用minKey表示任何不及格的分数:

db.restaurants.insertOne( [
{
_id: 1,
address: {
building: "230",
coord: [ -73.996089, 40.675018 ],
street: "Huntington St",
zipcode: "11231"
},
borough: "Brooklyn",
cuisine: "Bakery",
grades: [
{ date : new Date(1393804800000), grade : "C", score : 15 },
{ date : new Date(1378857600000), grade : "C", score : 16 },
{ date : new Date(1358985600000), grade : MinKey(), score : 30 },
{ date : new Date(1322006400000), grade : "C", score : 15 }
],
name : "Dirty Dan's Donuts",
restaurant_id : "30075445"
}
] )

And maxKey for any grade that is the highest passing grade:maxKey用于任何最高通过等级:

db.restaurants.insertOne( [
{
_id : 2,
address : {
building : "1166",
coord : [ -73.955184, 40.738589 ],
street : "Manhattan Ave",
zipcode : "11222"
},
borough: "Brooklyn",
cuisine: "Bakery",
grades: [
{ date : new Date(1393804800000), grade : MaxKey(), score : 2 },
{ date : new Date(1378857600000), grade : "B", score : 6 },
{ date : new Date(1358985600000), grade : MaxKey(), score : 3 },
{ date : new Date(1322006400000), grade : "B", score : 5 }
],
name : "Dainty Daisey's Donuts",
restaurant_id : "30075449"
}
] )

The following query returns any restaurant whose grades.grade field contains minKey or is an array containing an element of the specified type:以下查询返回其grades.grade字段包含minKey或是包含指定类型元素的数组的任何餐厅:

db.restaurants.find(
{ "grades.grade" : { $type : "minKey" } }
)

This returns the following results:这将返回以下结果:

{
_id : 1,
address : {
building : "230",
coord : [ -73.996089, 40.675018 ],
street : "Huntington St",
zipcode : "11231"
},
borough : "Brooklyn",
cuisine : "Bakery",
grades : [
{ date : ISODate("2014-03-03T00:00:00Z"), grade : "C", score : 15 },
{ date : ISODate("2013-09-11T00:00:00Z"), grade : "C", score : 16 },
{ date : ISODate("2013-01-24T00:00:00Z"), grade : { "$minKey" : 1 }, score : 30 },
{ date : ISODate("2011-11-23T00:00:00Z"), grade : "C", score : 15 }
],
name : "Dirty Dan's Donuts",
restaurant_id : "30075445"
}

The following query returns any restaurant whose grades.grade field contains maxKey or is an array containing an element of the specified type:以下查询返回其grades.grade字段包含maxKey或是包含指定类型元素的数组的任何餐厅:

db.restaurants.find(
{ "grades.grade" : { $type : "maxKey" } }
)

This returns the following results:这将返回以下结果:

{
_id : 2,
address : {
building : "1166",
coord : [ -73.955184, 40.738589 ],
street : "Manhattan Ave",
zipcode : "11222"
},
borough : "Brooklyn",
cuisine : "Bakery",
grades : [
{ date : ISODate("2014-03-03T00:00:00Z"), grade : { "$maxKey" : 1 }, score : 2 },
{ date : ISODate("2013-09-11T00:00:00Z"), grade : "B", score : 6 },
{ date : ISODate("2013-01-24T00:00:00Z"), grade : { "$maxKey" : 1 }, score : 3 },
{ date : ISODate("2011-11-23T00:00:00Z"), grade : "B", score : 5 }
],
name : "Dainty Daisey's Donuts",
restaurant_id : "30075449"
}

Querying by Array Type按数组类型查询

A collection named sensorReading contains the following documents:名为sensorReading(传感器读数)的集合包含以下文档:

db.sensorReading.insertMany( [
{ _id : 1, readings : [ 25, 23, [ "Warn: High Temp!", 55 ], [ "ERROR: SYSTEM SHUTDOWN!", 66 ] ] },
{ _id : 2, readings : [ 25, 25, 24, 23 ] },
{ _id : 3, readings : [ 22, 24, [] ] },
{ _id : 4, readings : [] },
{ _id : 5, readings : 24 }
] )

The following query returns any document in which the readings field is an array, empty or non-empty.以下查询返回readings字段为数组(空或非空)的任何文档。

db.SensorReading.find( { readings : { $type: "array" } } )

The above query returns the following documents:上述查询返回以下文档:

{
_id : 1,
readings : [
25,
23,
[ "Warn: High Temp!", 55 ],
[ "ERROR: SYSTEM SHUTDOWN!", 66 ]
]
},
{
_id : 2,
readings : [ 25, 25, 24, 23 ]
},
{
_id : 3,
readings : [ 22, 24, [] ]
},
{
_id : 4,
readings : []
}

In the documents with _id : 1, _id : 2, _id : 3, and _id : 4, the readings field is an array._id1_id2_id3_id4的文档中,readings字段是一个数组。

Additional Information附加信息