MongoDB $type 操作符
详解 MongoDB $type 操作符按 BSON 类型名称或数字代码过滤文档的语法、21 项完整 BSON 类型对照表、多类型数组匹配、$and 组合类型过滤及异构集合检索实战。
学完这一章,你能够
- 详解 MongoDB $type 操作符按 BSON 类型名称或数字代码过滤文档的语法、21 项完整 BSON 类型对照表、多类型数组匹配、$and 组合类型过滤及异构集合检索实战。
$type 操作符语法与 21 项 BSON 类型代码
由于 MongoDB 同一集合允许不同文档为同名字段存放不同类型的值,数据清洗与精确过滤常需要按实际 BSON 数据类型筛选。`$type` 操作符语法为 `db.collection.find({ field: { $type: <type> } })`:`field` 为待检测字段,`<type>` 既可传入 BSON 数字代码(如 `2`、`16`),也可传入可读性更高的字符串别名(如 `"string"`、`"int"`),或传入由多个类型构成的数组。下表列出 21 种常见 BSON 类型与编码(注意 `minKey` 在无符号字节表示中为 `255`,在有符号 BSON 规范及 MongoDB `$type` 数字参数中对应 `-1`)。
单类型、多类型数组与 $and 组合实例
日常最常用的单类型检索包括:按字符串过滤 `{ fieldName: { $type: "string" } }`(等价代码 `2`)、按 32 位整数过滤 `{ age: { $type: "int" } }`(等价代码 `16`;若需囊括所有数值类型,MongoDB 3.6+ 还支持聚合别名 `"number"`)、按布尔值过滤 `"bool"`(代码 `8`)以及按日期过滤 `"date"`(代码 `9`)。
MongoDB 支持向 `$type` 传入数组以匹配多种候选类型,例如 `{ value: { $type: ["string", "int"] } }` 或 `{ value: { $type: [2, 16] } }` 会同时召回字符串与整数型文档;也可配合 `$and` 对多个字段同时施加类型约束,例如要求 `details` 为内嵌对象(`"object"` / `3`)且 `score` 为双精度浮点数(`"double"` / `1`)。
异构集合字符串标题过滤实战
以包含多篇教程记录(如“PHP 教程”、“Java 教程”、“MongoDB 教程”)的集合 `col` 为例(演示写入在现代 `mongosh` 中推荐使用 `insertMany()` 替代历史 `insert()`),用 `db.col.find()` 核对全量记录后,执行 `db.col.find({ "title": { $type: 2 } })` 或 `db.col.find({ "title": { $type: "string" } })` 即可精准筛出所有 `title` 为字符串的文档并排除误写入数字等脏类型的记录。
MongoDB $type 支持的 BSON 类型代码与字符串别名对照
| 类型代码 | 类型名称(别名) |
| 1 | double(双精度浮点数) |
| 2 | string(UTF-8 字符串) |
| 3 | object(内嵌对象文档) |
| 4 | array(数组) |
| 5 | binData(二进制数据) |
| 6 | undefined(历史类型,已弃用) |
| 7 | objectId(12 字节 ObjectId) |
| 8 | bool(布尔值) |
| 9 | date(UTC 日期时间) |
| 10 | null(空值) |
| 11 | regex(正则表达式) |
| 12 | dbPointer(历史引用,已弃用) |
| 13 | javascript(JS 代码) |
| 14 | symbol(历史符号,已弃用) |
| 15 | javascriptWithScope(带作用域 JS,已弃用) |
| 16 | int(32 位有符号整数) |
| 17 | timestamp(64 位内部时间戳) |
| 18 | long(64 位有符号长整数) |
| 19 | decimal(128 位高精度十进制小数) |
| 255(有符号 -1) | minKey(BSON 最小键) |
| 127 | maxKey(BSON 最大键) |
运行 21 项 BSON $type 编码表、单/多类型过滤及异构集合字符串标题筛选验证
展开查看收起
"""Offline MongoDB $type BSON type codes & aliases verifier (Ch21 operators-type)."""
import datetime
import json
import re
VERSION = "CPython 3.12.14 offline MongoDB document/query verifier (mongod absent)"
BSON_TYPE_TABLE = [
(1, "double"),
(2, "string"),
(3, "object"),
(4, "array"),
(5, "binData"),
(6, "undefined"),
(7, "objectId"),
(8, "bool"),
(9, "date"),
(10, "null"),
(11, "regex"),
(12, "dbPointer"),
(13, "javascript"),
(14, "symbol"),
(15, "javascriptWithScope"),
(16, "int"),
(17, "timestamp"),
(18, "long"),
(19, "decimal"),
(255, "minKey"),
(127, "maxKey"),
]
CODE_TO_ALIAS = dict(BSON_TYPE_TABLE)
CODE_TO_ALIAS[-1] = "minKey" # Signed BSON code equivalent to unsigned 255
ALIAS_TO_CODE = {alias: code for code, alias in BSON_TYPE_TABLE}
class BsonObjectId(str):
pass
def detect_bson_type(val) -> str:
if isinstance(val, BsonObjectId):
return "objectId"
if isinstance(val, bool):
return "bool"
if isinstance(val, int):
return "int" if -(2**31) <= val <= (2**31 - 1) else "long"
if isinstance(val, float):
return "double"
if isinstance(val, str):
return "string"
if isinstance(val, list):
return "array"
if isinstance(val, dict):
return "object"
if isinstance(val, bytes):
return "binData"
if isinstance(val, datetime.datetime):
return "date"
if isinstance(val, re.Pattern):
return "regex"
if val is None:
return "null"
return "unknown"
def normalize_type_spec(spec) -> set[str]:
items = spec if isinstance(spec, list) else [spec]
out = set()
for it in items:
if isinstance(it, int):
out.add(CODE_TO_ALIAS[it])
else:
out.add(it)
return out
def match_type(doc: dict, field: str, spec) -> bool:
if field not in doc:
return False
allowed = normalize_type_spec(spec)
return detect_bson_type(doc[field]) in allowed
def case_bson_type_catalog_21_codes():
actual = {
"table_entries": len(BSON_TYPE_TABLE),
"code_2_is": CODE_TO_ALIAS[2],
"code_16_is": CODE_TO_ALIAS[16],
"minKey_signed_and_unsigned": [CODE_TO_ALIAS[-1], CODE_TO_ALIAS[255]],
"maxKey_code": ALIAS_TO_CODE["maxKey"],
}
expected = {
"table_entries": 21,
"code_2_is": "string",
"code_16_is": "int",
"minKey_signed_and_unsigned": ["minKey", "minKey"],
"maxKey_code": 127,
}
return {
"name": "bson_type_catalog_21_codes",
"summary": "核对全部 21 项 BSON 类型代码与字符串别名映射(含 minKey 255/-1 符号位差异说明)。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_single_type_code_and_alias_queries():
docs = [
{"id": 1, "fieldName": "hello", "age": 25, "isActive": True, "createdAt": datetime.datetime(2026, 1, 1)},
{"id": 2, "fieldName": 123, "age": "25", "isActive": 1, "createdAt": "2026-01-01"},
{"id": 3, "fieldName": None, "age": True, "isActive": False, "createdAt": datetime.datetime(2026, 6, 1)},
]
actual = {
"string_eq_code2": [d["id"] for d in docs if match_type(d, "fieldName", "string")]
== [d["id"] for d in docs if match_type(d, "fieldName", 2)],
"string_ids": [d["id"] for d in docs if match_type(d, "fieldName", 2)],
"int_excludes_bool": [d["id"] for d in docs if match_type(d, "age", "int")]
== [d["id"] for d in docs if match_type(d, "age", 16)]
and [d["id"] for d in docs if match_type(d, "age", 16)] == [1],
"bool_ids": [d["id"] for d in docs if match_type(d, "isActive", 8)],
"date_ids": [d["id"] for d in docs if match_type(d, "createdAt", "date")],
}
expected = {
"string_eq_code2": True,
"string_ids": [1],
"int_excludes_bool": True,
"bool_ids": [1, 3],
"date_ids": [1, 3],
}
return {
"name": "single_type_code_and_alias_queries",
"summary": "验证 string(2)、int(16)、bool(8)、date(9) 字符串别名与数字代码等价,并严格区分 bool 与 int。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_multi_type_array_and_and_combination():
docs = [
{"id": 1, "value": "text", "details": {"k": 1}, "score": 95.5},
{"id": 2, "value": 42, "details": {"k": 2}, "score": 90}, # int, not double
{"id": 3, "value": 3.14, "details": ["not_obj"], "score": 88.5},
]
by_alias = [d["id"] for d in docs if match_type(d, "value", ["string", "int"])]
by_code = [d["id"] for d in docs if match_type(d, "value", [2, 16])]
and_alias = [
d["id"]
for d in docs
if match_type(d, "details", "object") and match_type(d, "score", "double")
]
and_code = [
d["id"]
for d in docs
if match_type(d, "details", 3) and match_type(d, "score", 1)
]
actual = {
"multi_type_ids": by_alias,
"multi_type_matches_codes": by_alias == by_code,
"and_object_double_ids": and_alias,
"and_matches_codes": and_alias == and_code,
}
expected = {
"multi_type_ids": [1, 2],
"multi_type_matches_codes": True,
"and_object_double_ids": [1],
"and_matches_codes": True,
}
return {
"name": "multi_type_array_and_and_combination",
"summary": "验证 $type 数组多类型匹配(string/int 与 [2, 16])以及 $and 联合检查 object(3) 与 double(1)。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_tutorial_col_string_title_filter():
col = [
{"_id": BsonObjectId("56066542ade2f21f36b0313a"), "title": "PHP 教程", "likes": 200},
{"_id": BsonObjectId("56066549ade2f21f36b0313b"), "title": "Java 教程", "likes": 150},
{"_id": BsonObjectId("5606654fade2f21f36b0313c"), "title": "MongoDB 教程", "likes": 100},
{"_id": BsonObjectId("5606654fade2f21f36b0313d"), "title": 404, "likes": 0},
]
matched_code = [d["title"] for d in col if match_type(d, "title", 2)]
matched_name = [d["title"] for d in col if match_type(d, "title", "string")]
actual = {
"titles_by_code2": matched_code,
"equal_to_string_alias": matched_code == matched_name,
"oid_detected": detect_bson_type(col[0]["_id"]),
}
expected = {
"titles_by_code2": ["PHP 教程", "Java 教程", "MongoDB 教程"],
"equal_to_string_alias": True,
"oid_detected": "objectId",
}
return {
"name": "tutorial_col_string_title_filter",
"summary": "验证在混合类型集合中按 title: {$type: 2} 与 {$type: 'string'} 仅筛出 3 条字符串标题文档。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_bson_type_catalog_21_codes(),
case_single_type_code_and_alias_queries(),
case_multi_type_array_and_and_combination(),
case_tutorial_col_string_title_filter(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
字符串别名自解释性强、不易记错编码(尤其是 `minKey` 在无符号 `255` 与有符号 `-1` 间的差异),代码评审与长期维护成本显著低于裸数字代码。