MongoDB 使用逻辑运算符 — $and、$or、$not、$nor — 以及filter中多个字段的隐式AND来组合查询条件。这些运算符让您表达复杂的查询逻辑,以找到您需要的确切文档。
隐式AND(多个字段)
js
db..({ : , : { : } });
MongoDB 使用逻辑运算符 — $and、$or、$not、$nor — 以及filter中多个字段的隐式AND来组合查询条件。这些运算符让您表达复杂的查询逻辑,以找到您需要的确切文档。
db..({ : , : { : } });
最简单的情况:在filter中列出多个条件会隐式地对它们进行AND运算 — 所有条件都必须匹配。
// $or takes an array of conditions; a document matches if ANY is true
db.users.find({
$or: [
{ age: { $lt: 18 } },
{ age: { $gt: 65 } }
]
});
// → age < 18 OR age > 65
// usually implicit, but $and is needed when combining conditions on the SAME field
db.products.find({
$and: [
{ price: { $gt: 100 } },
{ price: { $lt: 500 } }
]
});
// (often you can write { price: { $gt: 100, $lt: 500 } } instead — cleaner)
// $and is also useful to combine $or groups:
db.users.find({
$and: [
{ $or: [{ role: "admin" }, { role: "editor" }] },
{ active: true }
]
});
db.products.find({ price: { $not: { $gt: 100 } } }); // NOT (price > 100) → price <= 100 or missing
db.users.find({ $nor: [{ active: true }, { premium: true }] }); // NEITHER condition true
// real queries combine logical + comparison operators
db.orders.find({
status: "shipped", // implicit AND
$or: [
{ total: { $gt: 1000 } },
{ priority: "high" }
]
});
// → status = shipped AND (total > 1000 OR priority = high)
逻辑运算符对于在MongoDB中表达复杂的查询条件是必不可少的 — 实际的查询通常需要多个条件(用AND/OR逻辑组合多个条件),因此理解它们是有效过滤数据的基础日常知识。
掌握多个filter字段的隐式AND(最简单、最常见的情况 — 列出必须全部匹配的条件)、$or(匹配多个条件中的任何一个 — 替代方案的常见需求)、$and(显式AND,需要在同一字段上组合条件或分组$or子句时使用)以及$not/$nor(否定)涵盖了表达查询需求的逻辑基础。
理解如何组合逻辑运算符和比较运算符(构建查询如"status shipped AND (total > 1000 OR priority high)")对于应用程序所需的实际多条件查询是必要的。
由于用组合条件过滤数据是常见需求(查找匹配复杂条件的文档),而MongoDB的逻辑运算符(隐式AND、$or、$and、$not/$nor)是表达此逻辑的方式 — 结合比较运算符用于实际条件 — 理解逻辑运算符是必不可少的、频繁应用的MongoDB知识,相当于掌握SQL WHERE子句中的AND/OR/NOT,对于用现实应用程序所需的通常复杂条件找到确切的文档是必要的。