MongoDB聚合運算符:$type
文章目錄
- MongoDB聚合運算符:$type
- 語法
- 使用
- 可用的類型
- 舉例
$type
聚合運算符用來返回指定參數的BSON類型的字符串。。
語法
{ $type: <expression> }
<expression>
可以是任何合法的表達式。
使用
- 不像查詢操作符
$type
基于BSON類型匹配數組元素,$type
聚合運算符不檢查數組元素,相反,當數組作為參數時,$type
聚合運算符返回參數的類型為array
。 - 如果參數為輸入文檔中不存在的字段,
$type
返回字符串"missing"
下面的表格顯示了$type
返回的一些常見類型的字符串:
示例 | 結果 |
---|---|
{ $type: "a" } | "string" |
{ $type: /a/ } | "regex" |
{ $type: 1 } | "double" |
{ $type: NumberLong(627) } | "long" |
{ $type: { x: 1 } } | "object" |
{ $type: [ [ 1, 2, 3 ] ] } | "array" |
可用的類型
類型 | 數字 | 別名 | 說明 |
---|---|---|---|
Double | 1 | “double” | |
String | 2 | “string” | |
Object | 3 | “object” | |
Array | 4 | “array” | |
Binary data | 5 | “binData” | |
Undefined | 6 | “undefined” | 已廢棄 |
ObjectId | 7 | “objectId” | |
Boolean | 8 | “bool” | |
Date | 9 | “date” | |
Null | 10 | “null” | |
Regular Expression | 11 | “regex” | |
DBPointer | 12 | “dbPointer” | 已廢棄 |
JavaScript | 13 | “javascript” | |
Symbol | 14 | “symbol” | 已廢棄 |
32-bit integer | 16 | “int” | |
Timestamp | 17 | “timestamp” | |
64-bit integer | 18 | “long” | |
Decimal128 | 19 | “decimal” | |
Min key | -1 | “minKey” | |
Max key | 127 | “maxKey” |
如果參數指定的字段在輸入文檔中不存在,$type
返回"missing"
舉例
coll
集合包含了下面的文檔:
{ _id: 0, a : 8 }
{ _id: 1, a : [ 41.63, 88.19 ] }
{ _id: 2, a : { a : "apple", b : "banana", c: "carrot" } }
{ _id: 3, a : "caribou" }
{ _id: 4, a : NumberLong(71) }
{ _id: 5 }
下面的聚合操作在$project
階段使用$type
運算符顯示字段a
的類型。
db.coll.aggregate([{$project: {a : { $type: "$a" }}
}])
執行的結果為:
{ "_id": 0, "a" : "double" }
{ "_id": 1, "a" : "array" }
{ "_id": 2, "a" : "object" }
{ "_id": 3, "a" : "string" }
{ "_id": 4, "a" : "long" }
{ "_id": 5, "a" : "missing" }