MongoDB 条件操作符
系统梳理 MongoDB 五大类条件操作符:8 个比较操作符、4 个逻辑操作符、2 个元素操作符、3 个数组操作符及正则/全文/地理空间/$where 其他操作符。
学完这一章,你能够
- 系统梳理 MongoDB 五大类条件操作符:8 个比较操作符、4 个逻辑操作符、2 个元素操作符、3 个数组操作符及正则/全文/地理空间/$where 其他操作符。
条件操作符分类与比较操作符
条件操作符是 MongoDB 查询语言(MQL)的表达核心,按职责分为五大类别:比较操作符、逻辑操作符、元素操作符、数组操作符,以及面向文本、正则与地理空间的其他操作符。
比较操作符共有 8 个,均以 `{ field: { $op: value } }` 形式作用于单个字段:`$eq`(等于)、`$ne`(不等于)、`$gt`(大于)、`$gte`(大于等于)、`$lt`(小于)、`$lte`(小于等于),以及集合成员判断 `$in`(字段值命中候选数组任一项,如 `{ age: { $in: [20, 25, 30] } }`)与 `$nin`(不在候选数组中)。
逻辑操作符与元素操作符
逻辑操作符共有 4 个:`$and` 要求数组内所有子条件同时成立(当对同一字段附加多个约束或组合嵌套表达式时尤为必要);`$or` 要求至少一个子条件成立;`$not` 对单字段操作符条件取反(需注意在 MongoDB 语义中 `{ age: { $not: { $gt: 25 } } }` 也会匹配不包含 `age` 字段的文档);`$nor` 要求数组内全部子条件均不成立。
元素操作符针对文档的无固定模式特性检查字段元数据:`$exists` 以布尔值判断文档是否包含指定键(区分显式存有 `null` 的字段与根本缺失该键的文档);`$type` 按 BSON 类型别名或数字代码精准筛选字段的实际存储类型(例如 `{ age: { $type: "int" } }`)。
数组操作符与正则、文本、地理空间及其他操作符
数组操作符专门处理列表与嵌套对象数组:`$all` 要求数组同时包含指定清单中的全部元素(与顺序无关,如 `{ tags: { $all: ["red", "blue"] } }` 或 `["mongodb", "database"]`);`$elemMatch` 要求数组中至少存在某一个元素同时满足多个子条件(避免对象数组里不同元素各自拼凑满足条件造成误命中);`$size` 精确匹配数组长度(如 `{ tags: { $size: 3 } }`,注意 `$size` 仅接受确定整数,不支持直接写范围比较)。
其余常用专项操作符包括:`$regex` 执行正则表达式匹配(如 `{ name: { $regex: /^John/ } }`);`$text` 在已建文本索引的字段上执行词元全文检索;`$where` 允许嵌入 JavaScript 表达式过滤(存在性能与安全风险,现代 MongoDB 强烈建议改用聚合 `$expr` 替代);地理空间查询则使用 `$near`(配合 `$maxDistance` 按距离近到远返回邻近点)与 `$geoWithin`(配合 `$centerSphere` 等几何体筛选区域内文档,须在位置字段建立 `2dsphere` 或 `2d` 索引)。
MongoDB 比较操作符速查表
| 操作符 | 语义描述 | 示例表达式 |
|---|---|---|
| $eq | 匹配字段值等于指定值的文档 | { age: { $eq: 25 } } |
| $ne | 匹配字段值不等于指定值(含缺失该字段)的文档 | { age: { $ne: 25 } } |
| $gt | 匹配字段值严格大于指定值的文档 | { age: { $gt: 25 } } |
| $gte | 匹配字段值大于或等于指定值的文档 | { age: { $gte: 25 } } |
| $lt | 匹配字段值严格小于指定值的文档 | { age: { $lt: 25 } } |
| $lte | 匹配字段值小于或等于指定值的文档 | { age: { $lte: 25 } } |
| $in | 匹配字段值命中给定数组任一元素的文档 | { age: { $in: [25, 30, 35] } } |
| $nin | 匹配字段值不在给定数组中(含缺失字段)的文档 | { age: { $nin: [25, 30, 35] } } |
MongoDB 逻辑操作符速查表
| 操作符 | 语义描述 | 示例表达式 |
|---|---|---|
| $and | 逻辑与,要求数组中所有条件全部成立 | { $and: [ { age: { $gt: 25 } }, { city: "New York" } ] } |
| $or | 逻辑或,满足数组中任意一个条件即命中 | { $or: [ { age: { $lt: 25 } }, { city: "New York" } ] } |
| $not | 逻辑非,对字段级表达式取反(同时命中缺少该字段的文档) | { age: { $not: { $gt: 25 } } } |
| $nor | 逻辑或非,要求数组中所有条件全部不成立 | { $nor: [ { age: { $gt: 25 } }, { city: "New York" } ] } |
MongoDB 元素操作符速查表
| 操作符 | 语义描述 | 示例表达式 |
|---|---|---|
| $exists | 检查文档是否包含指定键(即使值为 null 也算存在) | { age: { $exists: true } } |
| $type | 检查字段存储的实际 BSON 数据类型 | { age: { $type: "int" } } |
MongoDB 数组操作符速查表
| 操作符 | 语义描述 | 示例表达式 |
|---|---|---|
| $all | 要求数组包含指定列表中的全部元素(不限顺序) | { tags: { $all: ["red", "blue"] } } |
| $elemMatch | 要求数组内至少单个元素同时满足全部内嵌条件 | { results: { $elemMatch: { score: { $gt: 80, $lt: 85 } } } } |
| $size | 要求数组元素个数严格等于指定整数 | { tags: { $size: 3 } } |
MongoDB 正则、文本、脚本与地理空间操作符速查表
| 操作符 | 语义描述 | 示例表达式 |
|---|---|---|
| $regex | 按正则表达式匹配字符串字段 | { name: { $regex: /^A/ } } |
| $text | 基于文本索引执行分词全文检索 | { $text: { $search: "coffee" } } |
| $where | 使用 JavaScript 表达式过滤(已不推荐,优先改用 $expr) | { $where: "this.age > 25" } |
| $near | 按球面或平面距离查找靠近指定坐标的文档 | db.collection.find({ location: { $near: [10, 20], $maxDistance: 1000 } }) |
| $geoWithin | 查找落入指定几何区域内的地理坐标文档 | db.collection.find({ location: { $geoWithin: { $centerSphere: [[10, 20], 1] } } }) |
运行五大类共 22 个 MongoDB 条件操作符全覆盖离线验证
"""Offline MongoDB comparison, logical, element, array, regex/text/geo query operators verifier (Ch20)."""
import json
import math
import re
VERSION = "CPython 3.12.14 offline MongoDB document/query verifier (mongod absent)"
def bson_type_name(val) -> str:
if isinstance(val, bool):
return "bool"
if isinstance(val, int):
return "int"
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 val is None:
return "null"
return "unknown"
def eval_field_ops(doc: dict, field: str, cond: dict) -> bool:
present = field in doc
val = doc.get(field)
for op, target in cond.items():
if op == "$eq":
if not present or val != target:
return False
elif op == "$ne":
if present and val == target:
return False
elif op == "$gt":
if not (present and isinstance(val, (int, float)) and not isinstance(val, bool) and val > target):
return False
elif op == "$gte":
if not (present and isinstance(val, (int, float)) and not isinstance(val, bool) and val >= target):
return False
elif op == "$lt":
if not (present and isinstance(val, (int, float)) and not isinstance(val, bool) and val < target):
return False
elif op == "$lte":
if not (present and isinstance(val, (int, float)) and not isinstance(val, bool) and val <= target):
return False
elif op == "$in":
if not present or val not in target:
return False
elif op == "$nin":
if present and val in target:
return False
elif op == "$not":
if eval_field_ops(doc, field, target):
return False
elif op == "$exists":
if present != bool(target):
return False
elif op == "$type":
if not present or bson_type_name(val) != target:
return False
elif op == "$all":
if not (present and isinstance(val, list) and all(x in val for x in target)):
return False
elif op == "$size":
if not (present and isinstance(val, list) and len(val) == target):
return False
elif op == "$elemMatch":
if not (present and isinstance(val, list) and any(eval_query(el, target) for el in val if isinstance(el, dict))):
return False
elif op == "$regex":
if not (present and isinstance(val, str) and re.search(target, val)):
return False
return True
def eval_query(doc: dict, query: dict) -> bool:
for k, cond in query.items():
if k == "$and":
if not all(eval_query(doc, sub) for sub in cond):
return False
elif k == "$or":
if not any(eval_query(doc, sub) for sub in cond):
return False
elif k == "$nor":
if any(eval_query(doc, sub) for sub in cond):
return False
elif isinstance(cond, dict):
if not eval_field_ops(doc, k, cond):
return False
else:
if doc.get(k) != cond:
return False
return True
def haversine_meters(lon1, lat1, lon2, lat2) -> float:
r = 6371000.0
p1, p2 = math.radians(lat1), math.radians(lat2)
dp = math.radians(lat2 - lat1)
dl = math.radians(lon2 - lon1)
a = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2
return 2 * r * math.asin(math.sqrt(a))
def case_comparison_operators_all_eight():
docs = [
{"name": "u1", "age": 17},
{"name": "u2", "age": 20},
{"name": "u3", "age": 25},
{"name": "u4", "age": 30},
{"name": "u5", "age": 35},
]
q = lambda flt: [d["name"] for d in docs if eval_query(d, flt)]
actual = {
"$eq": q({"age": {"$eq": 25}}),
"$ne": q({"age": {"$ne": 25}}),
"$gt": q({"age": {"$gt": 25}}),
"$gte": q({"age": {"$gte": 25}}),
"$lt": q({"age": {"$lt": 25}}),
"$lte": q({"age": {"$lte": 25}}),
"$in": q({"age": {"$in": [20, 25, 30]}}),
"$nin": q({"age": {"$nin": [20, 25, 30]}}),
}
expected = {
"$eq": ["u3"],
"$ne": ["u1", "u2", "u4", "u5"],
"$gt": ["u4", "u5"],
"$gte": ["u3", "u4", "u5"],
"$lt": ["u1", "u2"],
"$lte": ["u1", "u2", "u3"],
"$in": ["u2", "u3", "u4"],
"$nin": ["u1", "u5"],
}
return {
"name": "comparison_operators_all_eight",
"summary": "逐一验证 $eq/$ne/$gt/$gte/$lt/$lte/$in/$nin 全部 8 个比较操作符。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_logical_operators_all_four():
docs = [
{"name": "a", "age": 16, "city": "Boston"},
{"name": "b", "age": 22, "city": "New York"},
{"name": "c", "age": 30, "city": "New York"},
{"name": "d", "age": 40, "city": "Chicago"},
{"name": "e", "city": "Miami"}, # missing age: matches $not:{$gt:25}!
]
q = lambda flt: [d["name"] for d in docs if eval_query(d, flt)]
actual = {
"$and": q({"$and": [{"age": {"$gt": 25}}, {"age": {"$lt": 35}}]}),
"$or": q({"$or": [{"age": {"$gt": 25}}, {"age": {"$lt": 18}}]}),
"$not": q({"age": {"$not": {"$gt": 25}}}),
"$nor": q({"$nor": [{"age": {"$gt": 25}}, {"age": {"$lt": 18}}]}),
}
expected = {
"$and": ["c"],
"$or": ["a", "c", "d"],
"$not": ["a", "b", "e"],
"$nor": ["b", "e"],
}
return {
"name": "logical_operators_all_four",
"summary": "验证 $and/$or/$not/$nor 四个逻辑操作符(含 $not 匹配缺失字段的 MongoDB 特性)。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_element_operators_exists_and_type():
docs = [
{"id": 1, "age": 25},
{"id": 2, "age": "25"},
{"id": 3, "age": None},
{"id": 4, "name": "no_age"},
]
actual = {
"exists_true": [d["id"] for d in docs if eval_query(d, {"age": {"$exists": True}})],
"exists_false": [d["id"] for d in docs if eval_query(d, {"age": {"$exists": False}})],
"type_int": [d["id"] for d in docs if eval_query(d, {"age": {"$type": "int"}})],
}
expected = {
"exists_true": [1, 2, 3],
"exists_false": [4],
"type_int": [1],
}
return {
"name": "element_operators_exists_and_type",
"summary": "验证 $exists(区分显式 null 与字段缺失)及 $type 精确匹配 BSON 整型字段。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_array_operators_all_elemmatch_size():
docs = [
{
"id": 1,
"tags": ["red", "blue", "green"],
"results": [{"score": 82}],
"items": [{"quantity": 12}],
},
{
"id": 2,
"tags": ["red", "yellow"],
"results": [{"score": 75}, {"score": 90}], # neither single element is in (80,85)
"items": [{"quantity": 5}],
},
{
"id": 3,
"tags": ["mongodb", "database", "nosql"],
"results": [{"score": 84}],
"items": [{"quantity": 20}],
},
]
actual = {
"all_red_blue": [d["id"] for d in docs if eval_query(d, {"tags": {"$all": ["red", "blue"]}})],
"all_mongo_db": [d["id"] for d in docs if eval_query(d, {"tags": {"$all": ["mongodb", "database"]}})],
"elemMatch_score_80_85": [
d["id"] for d in docs if eval_query(d, {"results": {"$elemMatch": {"score": {"$gt": 80, "$lt": 85}}}})
],
"elemMatch_qty_gt10": [
d["id"] for d in docs if eval_query(d, {"items": {"$elemMatch": {"quantity": {"$gt": 10}}}})
],
"size_3": [d["id"] for d in docs if eval_query(d, {"tags": {"$size": 3}})],
}
expected = {
"all_red_blue": [1],
"all_mongo_db": [3],
"elemMatch_score_80_85": [1, 3],
"elemMatch_qty_gt10": [1, 3],
"size_3": [1, 3],
}
return {
"name": "array_operators_all_elemmatch_size",
"summary": "验证 $all、$elemMatch(要求单个数组元素同时满足复合条件)与 $size 长度过滤。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_regex_text_geo_and_where_operators():
people = [
{"name": "John Doe", "bio": "Loves artisan coffee beans", "age": 30, "location": [10.002, 20.001]},
{"name": "Alice Wu", "bio": "Prefers green tea", "age": 22, "location": [10.5, 20.5]},
]
regex_hits = [p["name"] for p in people if eval_query(p, {"name": {"$regex": r"^John"}})]
text_hits = [p["name"] for p in people if "coffee" in re.findall(r"[a-z]+", p["bio"].lower())]
near_hits = [
p["name"]
for p in people
if haversine_meters(10.0, 20.0, p["location"][0], p["location"][1]) <= 1000.0
]
# $geoWithin $centerSphere radius in radians (1 radian ~= 6371 km)
within_sphere = [
p["name"]
for p in people
if (haversine_meters(10.0, 20.0, p["location"][0], p["location"][1]) / 6371000.0) <= 1.0
]
# Equivalent of $where "this.age > 25" without unsafe eval
where_equiv = [p["name"] for p in people if p["age"] > 25]
actual = {
"$regex": regex_hits,
"$text": text_hits,
"$near_1000m": near_hits,
"$geoWithin_1rad": within_sphere,
"$where_equiv_age_gt25": where_equiv,
}
expected = {
"$regex": ["John Doe"],
"$text": ["John Doe"],
"$near_1000m": ["John Doe"],
"$geoWithin_1rad": ["John Doe", "Alice Wu"],
"$where_equiv_age_gt25": ["John Doe"],
}
return {
"name": "regex_text_geo_and_where_operators",
"summary": "验证 $regex、词元化 $text、球面距离 $near/$geoWithin 与 $where 等价过滤语义。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_comparison_operators_all_eight(),
case_logical_operators_all_four(),
case_element_operators_exists_and_type(),
case_array_operators_all_elemmatch_size(),
case_regex_text_geo_and_where_operators(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 验证 8 个比较符、4 个逻辑符(含 $not 缺失字段)、$exists/$type、$all/$elemMatch/$size 及正则/文本/球面地理查询。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:2155ac48b1228f2e9efa66858f845cd18d0d442f698d544547347c78c287db03
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:f01178d70e42c099d92a51fa39d08a8e08398803fa20ad6c81cb7df303641d8f
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
文档 `{ results: [{ score: 75 }, { score: 90 }] }` 会被 `{ results: { $elemMatch: { score: { $gt: 80, $lt: 85 } } } }` 命中吗?为什么?
展开参考解答
不会命中;`$elemMatch` 要求数组中的**同一个元素**同时满足 `> 80` 且 `< 85`,而 `75` 与 `90` 均不落在该区间内。