MongoDB 查询文档
全面讲解 MongoDB find() 与 findOne() 查询语法、投影字段筛选、比较与逻辑操作符、正则表达式、排序分页链式组合、与 SQL WHERE 的对应关系以及 AND/OR 联合查询。
学完这一章,你能够
- 全面讲解 MongoDB find() 与 findOne() 查询语法、投影字段筛选、比较与逻辑操作符、正则表达式、排序分页链式组合、与 SQL WHERE 的对应关系以及 AND/OR 联合查询。
find() 与 findOne() 基础查询与格式化输出
MongoDB 查询集合文档主要依赖 `db.collection.find(query, projection)` 与 `db.collection.findOne(query, projection)`:第一参数 `query` 为过滤条件对象(默认 `{}` 匹配全部文档),第二参数 `projection` 为可选投影对象,用于指定包含(`1`)或排除(`0`)的返回字段(例如 `{ name: 1, age: 1, _id: 0 }` 仅返回姓名与年龄并隐藏默认 `_id`)。在旧版 `mongo` shell 中 `find()` 默认紧凑单行打印,常需链式附加 `.pretty()` 美化缩进;而在现代 `mongosh` 中查询结果默认已经格式化排版,`pretty()` 仅作兼容保留。
`findOne(query, projection)` 同样接收过滤条件与投影参数,但只返回命中的第一条文档对象(无匹配时返回 `null`),无需迭代游标,非常适合按主键或唯一业务键查询单条记录。
高级查询能力:比较、逻辑、正则、投影与游标链
MongoDB 查询表达式可灵活组合多种条件:比较操作符(`$gt`、`$lt`、`$gte`、`$lte`、`$eq`、`$ne`)用于数值与日期范围筛选,如 `{ age: { $gt: 25 } }`;逻辑操作符(`$and`、`$or`、`$not`、`$nor`)用于拼装多条件布尔逻辑;正则表达式(如 `{ name: /^A/ }`)直接对字符串字段执行模式匹配。
`find()` 返回游标后可继续链式组合投影、`.sort({ age: -1 })` 降序排列、`.skip(5)` 跳过前 5 条以及 `.limit(10)` 截取前 10 条。例如一条查询即可完成“筛选年龄大于 25 且城市为 New York 的文档 -> 仅投影 `name` 和 `age` 并隐藏 `_id` -> 按年龄降序 -> 取前 10 条”的完整业务检索。
与 SQL WHERE 对照及 AND / OR 联合查询
熟悉 SQL 的开发者可将 MongoDB 过滤文档直接映射为 `WHERE` 子句(详阅下方六类比较对照表)。在 `find()` 中,同一过滤对象内以逗号并列多个键值对即隐式构成 SQL `AND` 条件,例如 `{ by: "蓝色天空网", title: "MongoDB 教程" }` 等价于 `WHERE by = '蓝色天空网' AND title = 'MongoDB 教程'`。
表达逻辑“或”时使用 `$or` 关键字并传入条件数组,如 `{ $or: [{ by: "蓝色天空网" }, { title: "MongoDB 教程" }] }`;当需要同时表达 `AND` 与 `OR` 混合逻辑(如 `WHERE likes > 50 AND (by = '蓝色天空网' OR title = 'MongoDB 教程')`)时,只需在顶层对象中将普通字段条件与 `$or` 并列写出:`{ likes: { $gt: 50 }, $or: [{ by: "蓝色天空网" }, { title: "MongoDB 教程" }] }`。本站离线查询引擎已全部验证通过。
MongoDB 查询条件与 RDBMS SQL WHERE 语句对照
| 比较操作 | MongoDB 语法格式 | 查询范例 | SQL WHERE 等价写法 |
| 等于 | { <key>: <value> } | db.col.find({"by": "蓝色天空网"}) | WHERE by = '蓝色天空网' |
| 小于 | { <key>: { $lt: <value> } } | db.col.find({"likes": { $lt: 50 }}) | WHERE likes < 50 |
| 小于或等于 | { <key>: { $lte: <value> } } | db.col.find({"likes": { $lte: 50 }}) | WHERE likes <= 50 |
| 大于 | { <key>: { $gt: <value> } } | db.col.find({"likes": { $gt: 50 }}) | WHERE likes > 50 |
| 大于或等于 | { <key>: { $gte: <value> } } | db.col.find({"likes": { $gte: 50 }}) | WHERE likes >= 50 |
| 不等于 | { <key>: { $ne: <value> } } | db.col.find({"likes": { $ne: 50 }}) | WHERE likes != 50 |
运行 find/findOne 投影、六类 SQL WHERE 比较、AND/OR 组合、正则与游标链查询验证
展开查看收起
"""Offline MongoDB find/findOne, projection, $and/$or, regex & cursor chain verifier (Ch19 query)."""
import copy
import json
import re
VERSION = "CPython 3.12.14 offline MongoDB document/query verifier (mongod absent)"
def eval_filter(doc: dict, flt: dict) -> bool:
for k, cond in flt.items():
if k == "$and":
if not all(eval_filter(doc, sub) for sub in cond):
return False
elif k == "$or":
if not any(eval_filter(doc, sub) for sub in cond):
return False
else:
val = doc.get(k)
if isinstance(cond, dict):
for op, target in cond.items():
if op == "$gt" and not (isinstance(val, (int, float)) and val > target):
return False
elif op == "$gte" and not (isinstance(val, (int, float)) and val >= target):
return False
elif op == "$lt" and not (isinstance(val, (int, float)) and val < target):
return False
elif op == "$lte" and not (isinstance(val, (int, float)) and val <= target):
return False
elif op == "$eq" and val != target:
return False
elif op == "$ne" and val == target:
return False
elif op == "$regex" and not (isinstance(val, str) and re.search(target, val)):
return False
else:
if val != cond:
return False
return True
def apply_projection(doc: dict, proj: dict | None) -> dict:
if not proj:
return copy.deepcopy(doc)
non_id = {k: v for k, v in proj.items() if k != "_id"}
inclusion = any(v == 1 for v in non_id.values())
if inclusion:
out = {}
if proj.get("_id", 1) != 0 and "_id" in doc:
out["_id"] = doc["_id"]
for k, v in non_id.items():
if v == 1 and k in doc:
out[k] = copy.deepcopy(doc[k])
return out
out = copy.deepcopy(doc)
for k, v in proj.items():
if v == 0:
out.pop(k, None)
return out
USERS = [
{"_id": 1, "name": "Alice", "age": 28, "city": "New York"},
{"_id": 2, "name": "Aaron", "age": 34, "city": "New York"},
{"_id": 3, "name": "Bob", "age": 22, "city": "Chicago"},
{"_id": 4, "name": "Amy", "age": 31, "city": "New York"},
{"_id": 5, "name": "Carol", "age": 26, "city": "Boston"},
]
ARTICLES = [
{"_id": 101, "title": "MongoDB 教程", "by": "蓝色天空网", "likes": 100},
{"_id": 102, "title": "Python 教程", "by": "蓝色天空网", "likes": 50},
{"_id": 103, "title": "SQL 教程", "by": "其他作者", "likes": 30},
{"_id": 104, "title": "MongoDB 教程", "by": "社区投稿", "likes": 80},
]
def find(docs, flt=None, proj=None, sort_spec=None, skip=0, limit=0):
res = [d for d in docs if eval_filter(d, flt or {})]
if sort_spec:
for field, direction in reversed(sort_spec):
res.sort(key=lambda d: d[field], reverse=(direction == -1))
if skip:
res = res[skip:]
if limit:
res = res[:limit]
return [apply_projection(d, proj) for d in res]
def case_find_and_find_one_with_projection():
all_cnt = len(find(USERS))
gt25_proj = find(USERS, {"age": {"$gt": 25}}, {"name": 1, "age": 1, "_id": 0})
one_alice = find(USERS, {"name": "Alice"}, {"name": 1, "age": 1, "_id": 0}, limit=1)[0]
actual = {
"all_count": all_cnt,
"gt25_names": [d["name"] for d in gt25_proj],
"id_excluded": all("_id" not in d for d in gt25_proj),
"find_one_alice": one_alice,
}
expected = {
"all_count": 5,
"gt25_names": ["Alice", "Aaron", "Amy", "Carol"],
"id_excluded": True,
"find_one_alice": {"name": "Alice", "age": 28},
}
return {
"name": "find_and_find_one_with_projection",
"summary": "验证 find()、findOne() 与投影 {name: 1, age: 1, _id: 0} 的字段裁剪结果。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_comparison_and_rdbms_where_equivalence():
actual = {
"eq": [d["_id"] for d in find(ARTICLES, {"by": "蓝色天空网"})],
"lt50": [d["_id"] for d in find(ARTICLES, {"likes": {"$lt": 50}})],
"lte50": [d["_id"] for d in find(ARTICLES, {"likes": {"$lte": 50}})],
"gt50": [d["_id"] for d in find(ARTICLES, {"likes": {"$gt": 50}})],
"gte50": [d["_id"] for d in find(ARTICLES, {"likes": {"$gte": 50}})],
"ne50": [d["_id"] for d in find(ARTICLES, {"likes": {"$ne": 50}})],
}
expected = {
"eq": [101, 102],
"lt50": [103],
"lte50": [102, 103],
"gt50": [101, 104],
"gte50": [101, 102, 104],
"ne50": [101, 103, 104],
}
return {
"name": "comparison_and_rdbms_where_equivalence",
"summary": "验证等于、$lt、$lte、$gt、$gte、$ne 六类条件查询与 SQL WHERE 子句等价。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_and_or_combined_logic():
implicit_and = [d["_id"] for d in find(ARTICLES, {"by": "蓝色天空网", "title": "MongoDB 教程"})]
or_query = [d["_id"] for d in find(ARTICLES, {"$or": [{"by": "蓝色天空网"}, {"title": "MongoDB 教程"}]})]
combined = [
d["_id"]
for d in find(
ARTICLES,
{"likes": {"$gt": 50}, "$or": [{"by": "蓝色天空网"}, {"title": "MongoDB 教程"}]},
)
]
actual = {"implicit_and": implicit_and, "or_query": or_query, "and_or_combined": combined}
expected = {"implicit_and": [101], "or_query": [101, 102, 104], "and_or_combined": [101, 104]}
return {
"name": "and_or_combined_logic",
"summary": "验证逗号隐式 AND、$or 以及 likes>50 AND (by=... OR title=...) 联合逻辑过滤。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_regex_query_matching():
matched = [d["name"] for d in find(USERS, {"name": {"$regex": r"^A"}})]
expected = ["Alice", "Aaron", "Amy"]
return {
"name": "regex_query_matching",
"summary": "验证正则表达式 /^A/ 匹配所有以字母 A 开头的 name 字段。",
"expected": expected,
"actual": matched,
"passed": matched == expected,
}
def case_chained_sort_skip_limit_pipeline():
res = find(
USERS,
{"$and": [{"age": {"$gt": 25}}, {"city": "New York"}]},
{"name": 1, "age": 1, "_id": 0},
sort_spec=[("age", -1)],
skip=1,
limit=2,
)
expected = [{"name": "Amy", "age": 31}, {"name": "Alice", "age": 28}]
return {
"name": "chained_sort_skip_limit_pipeline",
"summary": "验证组合查询:$and 过滤 + 投影 + 按 age 降序 + skip(1).limit(2) 分页链式执行。",
"expected": expected,
"actual": res,
"passed": res == expected,
}
def main():
cases = [
case_find_and_find_one_with_projection(),
case_comparison_and_rdbms_where_equivalence(),
case_and_or_combined_logic(),
case_regex_query_matching(),
case_chained_sort_skip_limit_pipeline(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
MongoDB 投影不允许在同一个对象内同时包含普通字段的白名单(`1`)和黑名单(`0`);`_id: 0` 是官方唯一允许与包含式投影共存的例外。