MongoDB $type 操作符
$type操作符是基于BSON类型来检索集合中匹配的数据类型,并返回结果。
MongoDB 中可以使用的类型如下表所示:
类型 | 数字 | 备注 |
---|---|---|
Double | 1 | |
String | 2 | |
Object | 3 | |
Array | 4 | |
Binary data | 5 | |
Undefined | 6 | 已废弃。 |
Object id | 7 | |
Boolean | 8 | |
Date | 9 | |
Null | 10 | |
Regular Expression | 11 | |
JavaScript | 13 | |
Symbol | 14 | |
JavaScript (with scope) | 15 | |
32-bit integer | 16 | |
Timestamp | 17 | |
64-bit integer | 18 | |
Min key | 255 | Query with -1. |
Max key | 127 |
实例
集合 test 中的数据如下:
/* 1 */
{
"_id" : ObjectId("63e1bcd2da0f660d6928a74d"),
"id" : "1111",
"name" : "tom",
"age" : 22.0
}/* 2 */
{
"_id" : ObjectId("63e1bce1da0f660d6928a74e"),
"id" : "2222",
"name" : "jim",
"age" : 22.0
}/* 3 */
{
"_id" : ObjectId("63e35d6ada0f660d6928a74f"),
"id" : 21213.0,
"name" : "jack",
"age" : 25.0
}
获取 test集合中 id为 String 类型的数据,可以使用以下命令:
db.test.find({"id" : {$type : 2}}) 或 db.test.find({"id" : {$type : 'string'}})
输出结果为:
/* 1 */
{
"_id" : ObjectId("63e1bcd2da0f660d6928a74d"),
"id" : "1111",
"name" : "tom",
"age" : 22.0
}/* 2 */
{
"_id" : ObjectId("63e1bce1da0f660d6928a74e"),
"id" : "2222",
"name" : "jim",
"age" : 22.0
}
获取 test集合中 id为 Double 类型的数据,可以使用以下命令:
db.test.find({"id" : {$type : 1}})
或
db.test.find({"id" : {$type : 'double'}})
输出结果为:
/* 1 */
{
"_id" : ObjectId("63e35d6ada0f660d6928a74f"),
"id" : 21213.0,
"name" : "jack",
"age" : 25.0
}